How can I get the value of the input and turn it into the size of the grid squares? When I use the input value, my grid is messed up, but when I hard code the grid square size it works fine.
Here is a codepen: https://codepen.io/ryan_pixelers/pen/NbqKMQ
and here is the code:
// get our canvas
var grid = document.getElementById('grid');
hide(grid);
var horizontalSpace = 0;
var verticalSpace = 0;
var button = document.getElementById('gridControls');
button.onclick = drawCanvas;
function drawCanvas() {
show(grid);
var context = grid.getContext('2d');
// HERE: Why doesn't this work???
// var gridSize = document.getElementById('widthHeight').value;
var gridSize = 10;
// set the canvas style to positions absolute
// and set z-index high to keep it on top
grid.style.position = 'absolute';
grid.style.zIndex = '100000';
// get window width and height
var w = window.innerWidth;
var h = window.innerHeight;
// set the canvas width and height to be the window w/h
grid.width = w;
grid.height = h;
// create the horizontal lines
for(var horizontal = 0; horizontal < w; horizontal++) {
context.beginPath();
context.moveTo(0, horizontalSpace);
context.lineTo(w, horizontalSpace);
context.lineWidth = 1;
context.strokeStyle = "lightblue";
context.stroke();
horizontalSpace += gridSize;
}
// create the vertical lines
for(var vertical = 0; vertical < h; vertical++) {
context.beginPath();
context.moveTo(verticalSpace, 0);
context.lineTo(verticalSpace, h);
context.lineWidth = 1;
context.strokeStyle = "lightblue";
context.stroke();
verticalSpace += gridSize;
}
}
function hide(element) {
element.style.display = 'none';
}
function show(element) {
element.style.display = 'block';
}
Try uncommenting the line where I try to set gridSize as the value of the input field and see the result. It messes up the grid spaces!
Any idea how to remedy this?
Thanks!
好了,想通了:我需要在值上使用parseInt()。
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.