简体   繁体   中英

width and height in canvas are not accurate

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 ?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM