gpt4 book ai didi

javascript - 遍历 Canvas 中的颜色

转载 作者:行者123 更新时间:2023-11-30 09:32:52 25 4
gpt4 key购买 nike

我目前正在为我的智能播放器编写一些代码。然后我突然遇到了一个问题..我希望代码显示 7 个具有 7 种不同颜色的圆圈,与数组“颜色”相匹配。当我运行代码时,它只会返回数组中的绿色第一种颜色。谁能帮我解决这个问题?

var colors = ["green", "blue", "green", "green", "green", "green", "green"]; 
//Store all colors in a array to prevent loads of code
for (i = 0; i < colors.length; i++) {
console.log(colors[i]);
var centerX = ["325", "475", "625", "775", "925", "1075", "1225"];
//This will control the x-coordinate of the circles
for (p = 0; p < centerX.length; p++){
ctx.beginPath();
ctx.arc(centerX[p], centerY, radius, 0, 2 * Math.PI, false);
ctx.fillStyle = colors[i%2];
ctx.fill();
}

}

最佳答案

你让事情变得复杂了。可以简单地按如下方式完成......

var ctx = c.getContext('2d');

var colors = ["green", "blue", "green", "green", "green", "green", "green"];
var centerX = [325, 475, 625, 775, 925, 1075, 1225];
var centerY = 50;
var radius = 20;

for (i = 0; i < colors.length; i++) {
ctx.beginPath();
ctx.arc(centerX[i], centerY, radius, 0, 2 * Math.PI, false);
ctx.fillStyle = colors[i];
ctx.fill();
}
canvas { border: 1px solid black }
<canvas id="c" width="1300" height="100"></canvas>

关于javascript - 遍历 Canvas 中的颜色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45267502/

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