简体   繁体   English

HTML5 JavaScript:Canvas上下文在for循环中绘制栅格

[英]HTML5 javascript: canvas context draw raster in for loop

Boy, I feel really stupid today. 天哪,我今天真的很傻。 I just wanted to draw a raster (rows & columns) of different equally sized blocks on the HTML5 canvas. 我只是想在HTML5画布上绘制不同大小的块的栅格(行和列)。 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. 但是线条超出了我想在640x480尺寸的画布上绘制的512x384区域。 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 我现在也觉得很蠢: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: 使用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 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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