filip204
filip204

Reputation: 25

HTML5 Canvas - Why the color of the rectangle always returns black?

I want to draw a canvas rectangle that changes color every load. Here is my code:

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

Yet, every time when i open a web page, The color should changed to either red, blue or green but the color is persistently black.

Why is this happens? What is wrong in my code?

Upvotes: 1

Views: 1129

Answers (3)

DSCH
DSCH

Reputation: 2366

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

Upvotes: 1

Nina Scholz
Nina Scholz

Reputation: 386560

You need to take an integer value for accessing an array element.

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

I suggest to use the length of the array as factor for the random number (a constant vaue may go wrong if the count of elements changes later).

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

Upvotes: 2

Eli Richardson
Eli Richardson

Reputation: 930

You're not picking the random number correctly. Your random function will hardly ever return an integer.

Read more about Math.random here.

Here is what you're trying to do:

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>

Upvotes: 4

Related Questions