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

标签 javascript html canvas random

我想绘制一个每次加载都会改变颜色的 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/

相关文章:

javascript - 延迟的 HTML5 canvas javascript 问题

c# - 如何以编程方式更改 Canvas 的比例?

javascript - Canvas 中随时间变化的颜色(js)/setInterval 的问题

javascript - Mithril : Wrapping children in an array when using jsx

javascript - 在 javascript 中将日期转换为 JSON 时出现问题

javascript - 如何启用CSS光标:pointer (the hand symbol) in mobile/tablet browser (touch screen)

javascript - 单击鼠标在 Canvas 中绘制实心圆

javascript - d3.js 如何从 csv 或表生成树层次结构

javascript - 如何使用 jQuery 将 HTML 覆盖动态添加到表格行?

html - 在 Bootstrap 中垂直对齐左右元素