我有一个动画递归函数,该函数将正方形从画布的顶部移到底部。然后,我想通过使用ctx.fillStyle将其颜色更改为红色。它应该可以工作,但是程序流程中可能有错误。我看不到错误。也许,我不明白。
我使用了全局变量,并尝试在不同的地方调用该函数。
https://jsbin.com/cavuwak/edit?html,css,js,output
function init() {
setInterval(changeColor, 1000); }
function changeColor(){ ctx.fillStyle = 'red'; }
答案 0 :(得分:1)
您每秒将颜色更改为红色。但是每次调用animate()函数时,它都会将颜色更改回蓝色。 requestAnimationFrame(animate)大约每6ms-12ms触发一次,具体取决于您的硬件。 建议使用您的代码修复此问题:
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>