簡體   English   中英

HTML5 Canvas Grid-從輸入中獲取網格平方大小

[英]HTML5 Canvas Grid - Get Grid Square Size From Input

如何獲得輸入的值並將其轉換為網格正方形的大小? 當我使用輸入值時,我的網格被弄亂了,但是當我對網格平方大小進行硬編碼時,它可以正常工作。

這是一個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設置為輸入字段的值的行,並查看結果。 它弄亂了網格空間!

任何想法如何補救?

謝謝!

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM