跨像素的统一颜色?

Unified color across pixels?

我在我的代码中遇到了这个非常出乎意料的结果。

所以我只是写了一个简单的 JavaScript 脚本来在 640x400 大小的随机像素上写入随机颜色 HTML5 canvas。我希望它真的很有趣,因为屏幕上会出现各种不同的颜色。

但是当我在 3 个主要浏览器中尝试时,它们都给出了相同的结果:写入的像素始终是相同的颜色。每间隔 50 毫秒,它们都会同时改变颜色。虽然这很酷,但这不是故意的。

为什么我的代码会这样?

Colors.html:

<!DOCTYPE html>
<html>
<head>
<title>Colors</title>
<meta charset="UTF-8" />
</head>
<body>
<canvas width="640" height="400" id="canvas"></canvas>
<script src="./colors.js"></script>
</body>
</html>

colors.js:

document.body.style.backgroundColor = "black";

function $(id)
{
    return document.getElementById(id);
}

function getRandomInt(min, max) {
    return Math.floor(Math.random() * (max - min + 1)) + min;
}

var canvas = $("canvas"),
ctx = canvas.getContext("2d");

function setColor()
{
    ctx.fillStyle = "rgb(" + getRandomInt(0, 256) + "," + getRandomInt(0, 256) + "," + getRandomInt(0, 256) + ")";
    ctx.rect(getRandomInt(1, 639), getRandomInt(1, 399), 1, 1);
    ctx.fill();
}

setInterval(setColor, 50);

使用rect() 将向路径添加矩形。当使用fill()全部会被当前的fillStyle.

填充

rect()改为fillRect():

function setColor() {
    ctx.fillStyle = "rgb(" + getRandomInt(0, 256) + "," + getRandomInt(0, 256) + "," + getRandomInt(0, 256) + ")";
    ctx.fillRect(getRandomInt(1, 639), getRandomInt(1, 399), 1, 1);
}

您也可以在第一行使用 beginPath(),但对于 fillRect() 则没有必要,因为它不会向路径添加任何内容。对于样式一直在变化的情况,后者更快。

document.body.style.backgroundColor = "black";

function $(id)
{
    return document.getElementById(id);
}

function getRandomInt(min, max) {
    return Math.floor(Math.random() * (max - min + 1)) + min;
}

var canvas = $("canvas"),
ctx = canvas.getContext("2d");

    function setColor() {
        ctx.fillStyle = "rgb(" + getRandomInt(0, 256) + "," + getRandomInt(0, 256) + "," + getRandomInt(0, 256) + ")";
        ctx.fillRect(getRandomInt(1, 639), getRandomInt(1, 399), 1, 1);
    }

setInterval(setColor, 50);
<canvas width="640" height="400" id="canvas"></canvas>