Reputation: 25
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
Reputation: 2366
Try this: ctx.fillStyle = colors[Math.floor(Math.random() * colors.length)];
https://jsfiddle.net/xpavwkod/
Upvotes: 1
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
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