DevelopPHP.com
Web Development Training System

Canvas Animation Basics Tutorial

Learn the entry level basics of animation programming on the HTML canvas element using Javascript to perform the animated effect. The 3 basic steps to canvas tag animation programming are (1) Draw your assets (2) Clear the canvas (3) Redraw your assets into a new location or state of being. Your animation speed and fluidity depends on the time interval you set for a setTimeout() or setInterval() method in JavaScript. The requestAnimationFrame() is also a better interval choice for certain scenarios because it uses the browser default animation frame rate. <!-- http://www.youtube.com/watch?v=hUCT4b4wa-8 --> <!DOCTYPE html> <html> <head> <style> canvas{border:#666 1px solid;} </style> <script> function draw(x,y){ var canvas = document.getElementById('canvas'); var ctx = canvas.getContext('2d'); ctx.save(); ctx.clearRect(0,0,550,400); ctx.fillStyle = "rgba(0,200,0,1)"; ctx.fillRect (x, y, 50, 50); ctx.restore(); x += 1; var loopTimer = setTimeout('draw('+x+','+y+')',30); } </script> </head> <body> <button onclick="draw(0,0)">Draw</button> <canvas id="canvas" width="550" height="400"></canvas> </body> </html>
CanvasAnimationBasics