JavaScript循环在画布上创建网格

JavaScript Loop to create grid on canvas

本文关键字:创建 网格 循环 JavaScript      更新时间:2023-09-26

我要做的是用32x32块随机颜色填充myCanvas。我使用循环来创建块并为它们分配颜色。我已经知道如何在循环进行时使直线在Y轴上下降,但我无法想象如何使X轴正确。

如果你把画布变大,你会看到20个block的线条在右边。

var c=document.getElementById("myCanvas");
        var ctx=c.getContext("2d");
        for (i = 0; i < 400; i++) {
            var X = i * 32;
            var Y = Math.floor(i / 20) * 32;
            ctx.fillStyle='#'+Math.floor(Math.random()*16777215).toString(16);
            ctx.fillRect(X, Y, 32, 32);
            console.log('X:' + X);
            console.log('Y:' + Y);
        }

我试过这样使用模数:

if(i % 20 == 0){
X = 0;
}

但它只修复它,当我得到20的倍数,所以只有左侧的画布将被填充的块。我的问题是,我的脑子里全是完成这项工作所涉及的数学问题。对不起,我很累,这是一个新的

小提琴:http://jsfiddle.net/orwfo7re/

你已经非常接近你的模数建议了!然而,您的if语句只在 i % 20 == 0时执行,例如i=21

就不成立

解决方案是在你的算法中使用var x = (i % 20) * 32作为变量x。所以:

var c=document.getElementById("myCanvas");
var ctx=c.getContext("2d");
for (i = 0; i < 400; i++) {
     var X = (i % 20) * 32;
     var Y = Math.floor(i / 20) * 32;
     ctx.fillStyle='#'+Math.floor(Math.random()*16777215).toString(16);
     ctx.fillRect(X, Y, 32, 32);
}

小提琴:https://jsfiddle.net/MartyB/ur9vug0x/2/

你的意思是这样做吗?

var c=document.getElementById("myCanvas");
            var ctx=c.getContext("2d");
            var width = 640;
            var height = 640;
            for (y=0; y< height; y=y+32) {
                for (x=0; x < width; x=x+32) {
                ctx.fillStyle='#'+Math.floor(Math.random()*16777215).toString(16);
                ctx.fillRect(x, y, 32, 32);
                }
            }