Animated Background Layers on Canvas Tutorial

Published :
Author :
Adam Khoury
Learn to render animated background layers on your canvas with JavaScript. The background only needs to travel to its next tile, when it gets there we set it back to its starting position for a seamless effect. <!DOCTYPE html> <html> <head> <style> body{ background:#333; } #canvas_container{ width:1000px; margin: 20px auto; } #my_canvas{ background:#FFF; border:#999 1px solid; } </style> <script> var bg = new Image(); bg.src = "stars.jpg"; function initCanvas(){ var ctx = document.getElementById('my_canvas').getContext('2d'); var cW = ctx.canvas.width, cH = ctx.canvas.height; function Background(){ this.x = 0, this.y = 0, this.w = bg.width, this.h = bg.height; this.render = function(){ ctx.drawImage(bg, this.x--, 0); if(this.x <= -499){ this.x = 0; } } } var background = new Background(); function animate(){ ctx.save(); ctx.clearRect(0, 0, cW, cH); // Start drawing here background.render(); ctx.fillStyle = "orange"; ctx.fillRect(100,100,50,50); // End drawing here ctx.restore(); } var animateInterval = setInterval(animate, 30); } window.addEventListener('load', function(event) { initCanvas(); }); </script> </head> <body> <div id="canvas_container"><canvas id="my_canvas" width="1000" height="500"></canvas></div> </body> </html>