【问题标题】:HTML5 Canvas - Why the color of the rectangle always returns black?HTML5 Canvas - 为什么矩形的颜色总是返回黑色?
【发布时间】:2017-12-02 18:20:45
【问题描述】:

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

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);
}

然而,每次我打开网页时,颜色都应该变为红色、蓝色或绿色,但颜色始终是黑色。

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

【问题讨论】:

  • 你的随机程序很少返回整数

标签: javascript html canvas random


【解决方案1】:

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

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>

【讨论】:

    【解决方案2】:

    你需要一个整数值来访问一个数组元素。

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

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

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

    【讨论】:

      【解决方案3】:

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

      【讨论】:

        猜你喜欢
        • 2012-09-04
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-06-09
        • 2020-06-13
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多