像素统一颜色?

时间:2015-04-16 16:16:27

标签: javascript html5 canvas colors

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

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

但是当我在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);

1 个答案:

答案 0 :(得分:1)

使用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()不需要这样做,因为它不会向路径添加任何内容。对于风格一直在变化的情况,后者更快。

&#13;
&#13;
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);
&#13;
<canvas width="640" height="400" id="canvas"></canvas>
&#13;
&#13;
&#13;