2016-11-07 65 views
0

如何获取输入的值并将其转换为网格的尺寸?当我使用输入值时,我的网格被搞乱了,但是当我对网格正方形大小进行硬编码时,它工作正常。HTML5 Canvas Grid - 从输入中获取网格的方形尺寸

这里是一个codepen:https://codepen.io/ryan_pixelers/pen/NbqKMQ

这里是代码:

// 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'; 
} 

尝试在取消在那里我尝试设置gridSize作为输入字段的值,看看结果就行了。它弄乱了网格空间!

任何想法如何弥补这一点?

谢谢!

回答

0

好吧,想通了:我需要使用值的parseInt()。