Reputation: 103
I'm trying to use a pair of for loops generate a 4 by 4 array of 16 small rectangles each with a different color. However, the colors are not changing.
var x;
var y;
var color;
for (x=0; x < 4; x++){
for (y=0; y < 4; y++){
color = 255 - x*20 - y*20;
ctx.fillStyle = 'rgba(0, 0, color, 1.0)';
ctx.fillRect((x*10), (y*10), 10, 10);
}
}
Upvotes: 0
Views: 464
Reputation: 207557
You are setting it to the string color, not the variable. You need to fix how you are building the string.
var c=document.getElementById("myCanvas");
var ctx=c.getContext("2d");
var x;
var y;
var color;
for (x = 0; x < 4; x++) {
for (y = 0; y < 4; y++) {
color = 255 - x * 20 - y * 20;
ctx.fillStyle = 'rgba(0, 0, ' + color + ', 1.0)';
ctx.fillRect((x*10), (y*10), 10, 10);
}
}
<canvas id="myCanvas" width="300" height="150" style="border:1px solid #d3d3d3;">
Upvotes: 4
Reputation: 4278
color
is a string in the string you provide to fillStyle
, not the value of the variable color
. Here is the fixed version:
var x;
var y;
var color;
for (x=0; x < 4; x++){
for (y=0; y < 4; y++){
color = 255 - x*20 - y*20;
ctx.fillStyle = 'rgba(0, 0, ' + color + ', 1.0)'; // Here
ctx.fillRect((x*10), (y*10), 10, 10);
}
}
Upvotes: 1