Reputation: 1
Hi i'm attemting to create a grid in javascript/canvas but im having a few problems here's my code: 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);
This is the output:The grid so far I want it to fill the screen with rectangles.. Please help!:)
Upvotes: 0
Views: 100
Reputation: 68
If you're just trying to draw a grid of boxes, I'd recommend this:
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);
}
Upvotes: 2