[英]JavaScript Loop to create grid on canvas
我正在尝试用32x32的随机颜色块填充myCanvas。 我正在使用循环创建块并为其分配颜色。 我已经弄清楚了如何随着循环的进行而使线条在Y轴上下降,但是我无法绕过X轴正确的方向。
如果您将画布放大,您会看到右侧的行长为20个块。
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/
您是要执行以下操作吗?
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);
}
}
您已经非常接近模量建议! 但是,仅当 i % 20 == 0
时才执行if
语句,例如对于i=21
,这不是正确的
解决方案是在算法中仅对var x = (i % 20) * 32
使用var x = (i % 20) * 32
。 所以:
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);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.