簡體   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