简体   繁体   中英

How does the background change every n seconds?

he requestAnimationFrame function, updates the canvas too fast, so, I can not do what I want. What do I want ? I want to change the background color of the canvas, every 2 seconds, but the problem is that I am cleaning the canvas in each frame. What I can do ?

 (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> 

The issue is, you are initializing color timeout inside update which is being fired every second. So essentially, you are creating a new timeout every millisecond but this value is never been accepted as the moment color is updated, you reset its value to "" . Move the code to change background outside and use setInterval instead. So the process of creation of timers and updation of color is separate section and you will not override it in recursion.

Following is a sample

 (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> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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