Вы меняете цвет на красный раз в секунду.Но каждый раз, когда вызывается функция animate (), она снова меняет цвет на синий.requestAnimationFrame (animate) срабатывает примерно каждые 6 мс-12 мс в зависимости от вашего оборудования.Здесь предлагается исправить с помощью вашего кода:
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>