FULL STACK   ·   UI   ·   UX   ·   GRAPHICS   ·   DEVELOPER   ·   INSTRUCTOR

Adam Khoury

Donate funds to show love and support

Click the button below to donate funds securely online. You can use your PayPal account or a credit card.

Your donations help free up my time to produce more content and assist in covering server costs. It's also a great way to say thanks for the content!

Application Configuration

Adam will be adding options here soon.

Canvas Animation and App Initialization

Published :
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>