我使用canvas创建了一个网格制作器,到目前为止我有这个:
<-- HTML -->
<body>
<canvas id="tileMap"></canvas>
<form action="#">
<input type="range" max=5 min=1 name="numberOfTilesInLineAndColunm" id="numberOfTilesInLineAndColunm">
<script src="js.js"></script>
</form>
</body>
<-- JAVASCRIPT -->
window.onload = function() {
var grid = new Grid();
var input = document.getElementById('numberOfTilesInLineAndColunm');
canvas = document.getElementById("tileMap");
context = canvas.getContext("2d");
canvas.width = 300;
canvas.height = canvas.width;
//printGrid(grid.getGridBeginning(), grid.getGridSize(), grid.getTileSize());
input.addEventListener('change', function() {
grid.setNumberOfTilesInLineAndColunm();
grid.setGridSize();
printGrid(grid.getGridBeginning(), grid.getGridSize(), grid.getTileSize());
});
}
var canvas;
var context;
function Grid() {
var gridBeginning = 0;
var tileSize = 32;
var numberOfTilesInLineAndColunm = document.getElementById('numberOfTilesInLineAndColunm').value;
var gridSize = (numberOfTilesInLineAndColunm * tileSize);
var width = 0;
var height = 0;
this.getNumberOfTilesInLineAndColunm = function() {
return numberOfTilesInLineAndColunm;
}
this.setNumberOfTilesInLineAndColunm = function() {
numberOfTilesInLineAndColunm = document.getElementById('numberOfTilesInLineAndColunm').value;
}
this.getGridBeginning = function() {
return gridBeginning;
}
this.getTileSize = function() {
return tileSize;
}
this.getGridSize = function() {
return gridSize;
}
this.setGridSize = function() {
gridSize = (numberOfTilesInLineAndColunm * tileSize);
}
}
function printGrid(beginning, gridSize, squareSize) {
context.clearRect(0, 0, canvas.width, canvas.height);
for (beginning; beginning <= gridSize; beginning += squareSize) {
// printing the horizontal lines
context.moveTo(beginning, 0);
context.lineTo(beginning, gridSize);
context.stroke();
// printing the vertical lines
context.moveTo(0, beginning);
context.lineTo(gridSize, beginning);
context.stroke();
}
}
当我增加网格中的图块数量时,它工作正常,但是当我减少它时,它不会改变任何东西。
这是jsfiddle:http://jsfiddle.net/p54emnmg/
我要求你帮忙调试这个东西到目前为止我真的不知道错误在哪里。
答案 0 :(得分:2)
您必须在printGrid函数中执行context.beginPath()
。
beginPath
声明您正在启动一组新的路径绘制命令(如moveTo,lineTo)。
如果没有beginPath,每次调用context.stroke时都会重绘每个上一个绘图命令。
这意味着您总是绘制较大的网格,这会掩盖您想要的较小网格。
function printGrid(beginning, gridSize, squareSize) {
context.clearRect(0, 0, canvas.width, canvas.height);
// do context.beginPath();
// This starts a new path
// Without it, every previous drawing command is redrawn
context.beginPath();
for (beginning; beginning <= gridSize; beginning += squareSize) {
// printing the horizontal lines
context.moveTo(beginning, 0);
context.lineTo(beginning, gridSize);
context.stroke();
// printing the vertical lines
context.moveTo(0, beginning);
context.lineTo(gridSize, beginning);
context.stroke();
}
}