Object Oriented Assets OOP on Canvas

Published :
Author :
Adam Khoury
Learn how to add assets to your canvas in an object oriented manner to where each thing placed on the canvas is an object with unique property values such as its coordinates on the canvas, its fill color, dimensions and more. This allows us to more effectively treat our canvas assets as unique instances of objects and helps avoid value collisions when animating the property values of multiple assets simultaneously. <!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; // Constructor for rectangular assets function rectObj(){ this.x = 0, this.y = 0, this.w = 0; this.render = function(ctx, rx, ry, rw, rh, clr){ ctx.fillStyle = clr; ctx.fillRect(rx, ry, rw, rh); } } // Establish Assets outside of the animate function // to avoid re-creating them each time the function runs var rect1 = new rectObj(); var rect2 = new rectObj(); rect1.w = 50; rect2.w = 50; rect2.y = 100; function animate(){ ctx.clearRect(0, 0, cW, cH); // Draw here rect1.render(ctx, rect1.x, rect1.y, rect1.w, 50, "magenta"); rect2.render(ctx, rect2.x, rect2.y, rect2.w, 50, "blue"); rect1.x++; rect2.x++; } var animateInterval = setInterval(animate, 30); } window.addEventListener('load', function(event) { initCanvas(); }); </script> </head> <body> <canvas id="my_canvas" width="500" height="300"></canvas> </body> </html>