Reputation: 3
I am trying to add multiple colors to an array in an HTML5 canvas animation. I am using an if statement to add 3 different colors based on the array index, but the only color showing up is the "else" color (orange). Below is the code.
window.onload = function() {
var canvas = document.getElementById('myCanvas'),
context = canvas.getContext('2d'),
w = window.innerWidth,
h = window.innerHeight,
total = 100,
gumballs = [];
canvas.width = w;
canvas.height = h;
for(var i = 0; i < total; i++) {
gumballs.push({
x: Math.random()* w,
y: Math.random()* h,
r: Math.random()* 4+3,
d: Math.random()*total
})
}
function draw() {
context.clearRect(0,0,w,h);
context.beginPath();
for(var i = 0; i < total; i++) {
var s = gumballs[i];
if(s % 3 === 0){
context.fillStyle = 'blue';
} else if (s % 4 === 0) {
context.fillStyle = 'red';
} else {
context.fillStyle = "orange";
}
context.moveTo(s.x, s.y);
context.arc(s.x, s.y, s.r, 0, Math.PI*2, true);
}
context.fill();
update();
}
function update() {
for(var i = 0; i < total; i++) {
var s = gumballs[i];
s.y += 8;
if(s.x > w + 10 || s.x < - 10 || s.y > h) {
gumballs[i] = {x: Math.random()*w, y: 0, r: s.r, d: s.d};
}
}
}
setInterval(draw, 30);
}
Upvotes: 0
Views: 101
Reputation: 105015
You need to do .fill for each gumball rather than one .fill at the end:
function draw() {
context.clearRect(0,0,w,h);
for(var i = 0; i < total; i++) {
var s = gumballs[i];
if((i%3) == 0){
context.fillStyle = 'blue';
} else if ((i%4) == 0) {
context.fillStyle = 'red';
} else {
context.fillStyle = "orange";
}
context.beginPath();
context.moveTo(s.x, s.y);
context.arc(s.x, s.y, s.r, 0, Math.PI*2, true);
context.fill();
}
update();
}
Upvotes: 1
Reputation: 171679
You state you want to set color based on array index so your if
should be checking index, not the array element at that index
Try changing:
if(s % 3 === 0){
To:
if(i % 3 === 0){
Same for other if
Upvotes: 0
Reputation: 8550
It looks like gumballs[i] will always be an object - {x, y, r, d} - and so s % 3 and s % 4 will be NaN, causing the code to fall to the else clause.
Upvotes: 0