Reputation: 99
I have an animate recursive function that moves the square from the top of the canvas to the bottom. Then, I want to change its color to red using ctx.fillStyle. I can't see the error. Or perhaps, i'm not understanding something.
I used global variables and tried to call the function in diferents places.
https://jsbin.com/cavuwak/edit?html,css,js,output
function init() {
setInterval(changeColor, 1000); }
function changeColor(){ ctx.fillStyle = 'red'; }
Upvotes: 1
Views: 2715
Reputation: 117
You are changing the colour to red once every second. But every time the function animate() is called, it changes the colour back to blue. requestAnimationFrame(animate) fires approx every 6ms-12ms depending on your hardware. Here is proposed fix using your code:
var canvas, ctx, squareY = 10;
var currentColor = 0;
var colors = ['blue', 'red', 'green'];
//First change: add variable to hold current color
var color = 0;
window.onload= init;
function init() {
canvas = document.querySelector('#myCanvas');
ctx = canvas.getContext('2d');
drawTwoRect();
requestAnimationFrame(animate);
var a = setInterval(changeColor, 1000);
}
function drawTwoRect() {
ctx.fillStyle = 'green';
ctx.fillRect(10,10,100,100);
ctx.fillStyle = 'red';
ctx.fillRect(120,10,60,60);
}
function animate() {
ctx.clearRect(0,0, canvas.width,canvas.height);
//Second change: use your array colors to change the color.
ctx.fillStyle = colors[color];
ctx.fillRect(190,squareY,30,30);
squareY++;
if(squareY === 100) squareY = 0;
requestAnimationFrame(animate);
}
function changeColor() {
//Third change: flip the value in global color. Like this, the square changes its color every second.
color = Math.abs(color-1);
// if you want to change the color only once, just set color = 1:
// color = 1;
}
#myCanvas {
border: 2px dotted
}
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>JS Bin</title>
</head>
<body>
<canvas id="myCanvas" width=300px heigth=300px >
We usually write a small message</canvas>
</body>
</html>
Upvotes: 1