(function(d, w) {
var canvas = d.getElementsByTagName("CANVAS")[0],
ctx = canvas.getContext("2d");
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
var x = 0,
y = 0,
speedX = .9;
update(x, y, speedX);
function update(x, y, speedX) {
var color = "";
setTimeout(function() { // Here i try set the color each 2s
color = randomColor(); // Need the color here
}, 2000);
ctx.fillStyle = color; // here paint the background
ctx.fillRect(0, 0, canvas.width, canvas.height); // paint
x += speedX;
box(x, y, speedX);
requestAnimationFrame(function() { // animation frame
update(x, y, speedX);
});
}
function box(x, y, speedX) {
ctx.fillStyle = "Black";
ctx.fillRect(+x, +y, 50, 50);
ctx.stroke();
}
function randomColor() {
for (var i = 0, str = "", hex = "0123456789ABCDEF",
random, max = hex.length; i < 6; i++, random =
Math.floor(Math.random() * max), str += hex[random]);
return "#" + str;
}
})(document, window);
&#13;
<canvas></canvas>
&#13;
答案 0 :(得分:0)
问题是,您正在color
内初始化update
超时,这是每秒被触发的。基本上,您每隔毫秒创建一个新的超时,但是当color
更新的时刻,您的值重置为""
时,该值永远不会被接受。移动代码以更改外部背景并改为使用setInterval
。因此,创建计时器和更新颜色的过程是单独的部分,您不会在递归中覆盖它。
以下是一个示例
(function(d, w) {
var canvas = d.getElementsByTagName("CANVAS")[0],
ctx = canvas.getContext("2d");
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
var x = 0,
y = 0,
speedX = .9;
update(x, y, speedX);
var color = randomColor();
setInterval(function() { // Here i try set the color each 2s
color = randomColor(); // Need the color here
}, 2000);
function update(x, y, speedX) {
requestAnimationFrame(function() { // animation frame
ctx.fillStyle = color; // here paint the background
ctx.fillRect(0, 0, canvas.width, canvas.height); // paint
x += speedX;
box(x, y, speedX);
update(x, y, speedX);
});
}
function box(x, y, speedX) {
ctx.fillStyle = "Black";
ctx.fillRect(+x, +y, 50, 50);
ctx.stroke();
}
function randomColor() {
for (var i = 0, str = "", hex = "0123456789ABCDEF",
random, max = hex.length; i < 6; i++, random =
Math.floor(Math.random() * max), str += hex[random]);
return "#" + str;
}
})(document, window);
<canvas></canvas>