我想绘制一个每次加载都会改变颜色的 Canvas 矩形。这是我的代码:
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);
}
然而,每次我打开网页时,颜色应该变为红色、蓝色或绿色,但颜色一直是黑色。
为什么会这样?我的代码有什么问题?
最佳答案
您没有正确选择随机数。您的随机函数几乎不会返回整数。
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>
关于javascript - HTML5 Canvas - 为什么矩形的颜色总是返回黑色?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47611055/