您好我想在javascript / canvas中创建一个网格,但我在这里遇到一些问题是我的代码: var canvas = document.getElementById(" canvas"); var ctx = canvas.getContext(" 2d");
var width = 600;
var height = 700;
canvas.width=width;
canvas.height=height;
function Cell(x,y,width,height){
this.x=x;
this.y=y;
this.width=width;
this.height=height;
this.draw=function(){
ctx.rect(this.x,this.y,this.width,this.height);
ctx.stroke();
}
}
var x = 0;
var y = 0;
var width = 20;
var height = 20;
var cell = new Cell(x,y,width,height);
var rows = 35;
var cols = 30;
function drawGrid(){
for(var i=0; i<rows; i++){
for(var j=0; j<cols; j++){
cell.y+=cell.height;
cell.x+=cell.width;
cell.draw();
}
}
}
setInterval(drawGrid,1);
这是输出:The grid so far 我希望它用矩形填满屏幕..请帮助!:)
答案 0 :(得分:1)
如果您只是想绘制盒子网格,我建议您这样做:
var c = document.getElementById("myCanvas");
var ctx = c.getContext("2d");
//change these if you dont want to fill the whole canvas
var h = c.height; //height of grid
var w = c.width; //width of grid
var div=20; //box size
for(i=0; i<h/div+1; i++){
//Horizontal Line
ctx.moveTo(0,i*div);
ctx.lineTo(h,i*div);
//Vertial Line
ctx.moveTo(i*div,0);
ctx.lineTo(i*div,w);
}