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.

JSON Object Arrays and Loops on Canvas

Published :
Author :
Adam Khoury
Learn to put JSON objects, arrays and loops to work in your canvas applications. JSON objects are a great way to group and keep track of many objects as individual entities on the canvas that can possess any properties you wish. Packing those JSON objects into arrays makes it simple to add or remove them from a particular related group of objects from the canvas when needed. <!DOCTYPE html> <html> <head> <style> body{ background:#333; } #my_canvas{ background:#FFF; border:#999 1px solid; } </style> <script> function initCanvas(){ var ctx = document.getElementById('my_canvas').getContext('2d'); var buildings = [ {"id":"house","x":100,"y":100,"w":50,"h":50,"bg":"magenta"}, {"id":"grocery","x":200,"y":100,"w":50,"h":50,"bg":"green"}, {"id":"post_office","x":300,"y":100,"w":50,"h":50,"bg":"orange"} ]; for(var i = 0; i < buildings.length; i++){ var b = buildings[i]; ctx.fillStyle = b.bg; ctx.fillRect(b.x,b.y,b.w,b.h); } } window.addEventListener('load', function(event) { initCanvas(); }); </script> </head> <body> <canvas id="my_canvas" width="500" height="300"></canvas> </body> </html>