HTML5 Canvas - 为什么矩形的颜色总是返回黑色?

时间:2017-12-02 18:20:45

标签: javascript html5 canvas random

我想画一个画布矩形,每次加载都会改变颜色。这是我的代码:

window.onload = function() {
    var can = document.getElementById("lol");
    var ctx = can.getContext("2d");
    var colors = ["rgba(255,0,0,1)", "rgba(0,255,0,1)", "rgba(0,0,255,1)"];

    ctx.fillStyle = colors[Math.random() * 3];
    ctx.fillRect(40,40,30,25);
}

然而,每当我打开网页时,颜色应该变为红色,蓝色或绿色,但颜色会持续变黑。

为什么会这样?我的代码有什么问题?

3 个答案:

答案 0 :(得分:4)

您没有正确选择随机数。你的随机函数几乎不会返回整数。

Read more about Math.random here.

以下是您尝试做的事情:



var can = document.getElementById("lol");
var ctx = can.getContext("2d");
var colors = ["rgba(255,0,0,1)", "rgba(0,255,0,1)", "rgba(0,0,255,1)"];

ctx.fillStyle = colors[Math.floor(Math.random() * 3)];
ctx.fillRect(40,40,30,25);

<canvas id="lol"></canvas>
&#13;
&#13;
&#13;

答案 1 :(得分:2)

您需要获取一个整数值来访问数组元素。

ctx.fillStyle = colors[Math.floor(Math.random() * 3)];

我建议使用数组的长度作为随机数的因子(如果元素的数量稍后改变,则常数可能会出错)。

ctx.fillStyle = colors[Math.floor(Math.random() * colors.length)];

答案 2 :(得分:1)

试试这个:ctx.fillStyle = colors[Math.floor(Math.random() * colors.length)]; https://jsfiddle.net/xpavwkod/

相关问题