gpt4 book ai didi

使用 ctx 的带有交替颜色列的 Javascript 绘图板

转载 作者:行者123 更新时间:2023-12-04 02:07:02 26 4
gpt4 key购买 nike

我想编写一个 javascript 代码,使电路板显示为这张图片中的样子: 1
到目前为止,这是我的代码:

function draw() {
var canvas = document.getElementById('canvas');
var ctx = canvas.getContext('2d');
var x, y;

for (y=0; y<100; y+=10) {
for (x=0; x<100; x+=5) {
if ((x+y)%10 == 0) {
ctx.fillStyle = "black";
}
else {
ctx.fillStyle = "white";
}
ctx.fillRect(x, y, 10, 10);
}
}
}

到目前为止,它只显示垂直线。我需要进行哪些更改才能使其看起来像图像?

最佳答案

您应该将 x 值除以增量 (10) 并检查其模数 2:

function draw() {
var canvas = document.getElementById('canvas');
var ctx = canvas.getContext('2d');

for (var y = 0; y < 100; y += 10) {
for (var x = 0; x < 100; x += 10) {
if ((x/10) % 2 == 0) {
ctx.fillStyle = "black";
} else {
ctx.fillStyle = "red";
}
ctx.fillRect(x, y, 7, 7);
}
}
}
draw()
<canvas id="canvas" height="100" width="100"></canvas>

关于使用 ctx 的带有交替颜色列的 Javascript 绘图板,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30747395/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com