Reputation: 2285
I'm trying to draw a canvas with width x*100px
and height y*100px
var x=6,y=5;
var canvas = document.getElementById('game');
var ctx = canvas.getContext('2d');
canvas.style.width=(100*x)+"px";
canvas.style.height=(100*y)+"px";
for(var i=0;i<x;i++)
for(var j=0;j<y;j++)
{
ctx.fillStyle = "rgb(200,0,0)";
ctx.fillRect (i*100, j*100, 100, 100);
ctx.fillStyle = "rgb(0,0,0)";
ctx.strokeRect(i*100, j*100, 100, 100);
}
jsfiddle
but it looks like the width and height of each tile in the grid are not 100 px
, Why is that? and how can I set the width of each tile exactly to 100px
?
Upvotes: 1
Views: 93
Reputation: 8610
Use this instead:
canvas.width=(100*x);
canvas.height=(100*y);
It seems a bit strange, but canvas
is one element type that does not use CSS styling for its width and height. The number of available physical pixels is very relevant to the way that it draws, so it can't be left as a transient, derived CSS value (ie, width: calc(300vw - 100% - 20px);
). That said, it's usually a good idea to have width/height change on a browser resize if you're making the web page responsive.
Upvotes: 2