繁体   English   中英

背景每隔n秒如何变化?

[英]How does the background change every n seconds?

他的requestAnimationFrame函数太快地更新了画布,所以,我不能做我想做的事。 我想要什么 ? 我想每2秒更改一次画布的背景颜色,但是问题是我正在清洁每一帧中的画布。 我可以做什么 ?

 (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); 
 <canvas></canvas> 

问题是,您正在初始化每秒update一次的update内部的color超时。 因此,从本质上讲,您正在每毫秒创建一个新的超时,但是在更新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> 

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM