Atu Touato
Atu Touato

Reputation: 3

Unified color across pixels?

I came across this really unexpected result in my code.

So I was just writing a simple JavaScript script to write random colors on random pixels in a 640x400 size HTML5 canvas. I expected it to be really fun because there would be all different colors all across the screen.

But when I tried it out in 3 major browsers, all of them gave the same result: That the pixels written were always the same color. With each 50 millisecond interval, they all changed color in unison. While this is cool, this is not intended.

Why is my code acting this way?

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

Upvotes: 0

Views: 35

Answers (1)

user1693593
user1693593

Reputation:

Using rect() will add rectangles to a path. When fill() is used all of them will be filled with the current fillStyle.

Change rect() to 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);
}

You could also have used beginPath() at the first line, but this is not necessary with fillRect() as it doesn't add anything to the path. The latter is faster for cases where style is changed all the time.

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>

Upvotes: 1

Related Questions