Boy, I feel really stupid today. I just wanted to draw a raster (rows & columns) of different equally sized blocks on the HTML5 canvas. Something I though I've done many times before, but for some reason I cannot figure out the logic to get it to work!

To get an idea of where the blocks will be placed, I thought I'd started out drawing different rectangles in the raster. But the lines go beyond the 512x384 area I wanted to draw in on my 640x480 sized canvas. It's like the rectangles get drawn too big!

I am sure there is something really simply I'm overlooking, but I cannot see it!

context.fillStyle="black";
context.fillRect(0, 0, 640, 480);
for (var x = 0; x<512; x=x+16)
{
    for(var y = 0; y<384; y=y+24)
    {
        context.beginPath();
        context.rect(x,y,x+16,y+24);
        context.strokeStyle="green";
        context.stroke();
    }
}
有帮助吗?

解决方案

Are you sure you want to do this part?

context.rect(x,y,x+16,y+24);

Or maybe you intended this:

context.rect(x,y,16,24);

其他提示

I'm now feeling stupid too :D
Tried hard but didn't find our problem...
However, I came up with a simpler way of drawing the raster: drawing all lines seperately.

Javascript:

function drawRaster(){
var canv = document.getElementById("mycanvas");
var context = canv.getContext("2d");
var rectWidth = 16;
var rectHeight = 24;
var frameWidth = 512;
var frameHeight = 384;

context.fillStyle="black";
context.fillRect(0, 0, 640, 480);
context.strokeStyle="green";
context.lineWidth = 1;

for (var x = 0, x<=frameWidth, x+=rectWidth){ // Drawing all vertical lines
context.beginPath();
context.moveTo(x,0);
context.lineTo(x,frameHeight);
context.stroke();
}

for (var y = 0, y<=frameHeight, y+=rectHeight){ // Drawing all horizontal lines
context.beginPath();
context.moveTo(0,y);
context.lineTo(frameWidth,y);
context.stroke();
}
}

-- THIS IS STILL NOT WORKING, BUT IMPROVED CONCEPT--

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top