Hosting Solutions
mobile_logo Table of Contents
seal_frontseal_back

Animated Background Layers on Canvas Tutorial

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

JavaScript Videos

Canvas Programming

2D Context Object and Rectangle MethodsFill and Stroke Styles Color Gradient PatternLine Styles for Lines and StrokesBuilding and Drawing PathsDrawing Images and VideosDrawing Text on CanvasRendering Shadows on CanvasCanvas Transformation EffectsPixel Manipulation on CanvasCompositing on the CanvasDynamic Centering and Alignment on the CanvasCanvas Animation and App InitializationObject Oriented Assets OOP on CanvasDetect Mouse Coordinates on CanvasAnimated Background Layers on Canvas TutorialKeyboard Control and MovementJSON Object Arrays and Loops on CanvasHit Detection Mouse Touch Over Object ArraysCollision Detection Hit Game EnemiesParticle Effect System Tutorial Snow Falling AnimationInteractive Canvas Imaging Applications JavaScript PHP TutorialCircular Progress Loader Canvas JavaScript Programming Tutorial