我想绘制一个更改每个负载颜色的画布矩形。这是我的代码:
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);
}
然而,每当我打开网页时,颜色都应更改为红色,蓝色或绿色,但颜色持续黑色。
为什么会发生这种情况?我的代码中有什么问题?
您未正确选择随机数。您的随机功能几乎不会返回整数。
在此处阅读有关Math.random的更多信息。
这是您要做的:
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>
您需要采用一个整数值以访问数组元素。
ctx.fillStyle = colors[Math.floor(Math.random() * 3)];
我建议将数组的长度用作随机数的因子(如果元素计数更改,则常数vaue可能会出错)。
ctx.fillStyle = colors[Math.floor(Math.random() * colors.length)];
尝试以下: ctx.fillStyle = colors[Math.floor(Math.random() * colors.length)];
https://jsfiddle.net/xpavwkod/