Canvas Animation and App Initialization

Adam Khoury Published : November 17, 2014
Last Edited : November 24, 2025
Author : Adam Khoury
Learn to structure your JavaScript for animation programming on the canvas, and how to initialize canvas applications in order to place all of your JavaScript in the head section of the document to keep your documents logical and tidy. <!DOCTYPE html> <html> <head> <style> body{ margin:10px; background:#CCC; } #my_canvas{ background:#FFF; border:#000 1px solid; } </style> <script> function initCanvas(){ var ctx = document.getElementById('my_canvas').getContext('2d'); var cW = ctx.canvas.width, cH = ctx.canvas.height; var y = 0, x = 0; function animate(){ ctx.save(); ctx.clearRect(0, 0, cW, cH); // Draw here ctx.rotate(-.1); ctx.fillStyle = "magenta"; ctx.fillRect(0, y, 50, 50); ctx.rotate(.3); ctx.fillStyle = "blue"; ctx.fillRect(x, 0, 50, 50); y++; x++; ctx.restore(); } var animateInterval = setInterval(animate, 30); ctx.canvas.addEventListener('click', function(event) { clearInterval(animateInterval); }); } window.addEventListener('load', function(event) { initCanvas(); }); </script> </head> <body> <canvas id="my_canvas" width="500" height="300"></canvas> </body> </html>