javascript - 遍历 Canvas 中的颜色

标签 javascript arrays canvas colors

我目前正在为我的智能播放器编写一些代码。 然后我突然遇到了一个问题.. 我希望代码显示 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/

相关文章:

javascript - 如何在队列中存储ajax值

javascript - 在组件中使用 ngx-translate

javascript - ExtJS 网格行特定的 EmptyText?

php - 如何在 PHP 中返回从 MySQL 获取的数组

c - 指向引用加上数组之一的指针

javascript - 在继续之前等待图像加载

javascript - 获取图 block 集上图 block 的 X 和 Y

javascript - 用js代码设置鼠标位置并将该位置放在其他js代码中

javascript - 绘制贝塞尔曲线但 Canvas 保持空白

python - 随机分割数据以用于该函数的训练和测试