Hosting Solutions
mobile_logo Table of Contents

JSON Object Arrays and Loops on Canvas

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 =; 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>

JavaScript Videos

Canvas Programming

2D Context Object and Rectangle MethodsFill and Stroke Styles Color Gradient PatternLine Styles for Lines and StrokesBuilding and Drawing PathsDrawing Images and VideosDrawing Text on CanvasRendering Shadows on CanvasCanvas Transformation EffectsPixel Manipulation on CanvasCompositing on the CanvasDynamic Centering and Alignment on the CanvasCanvas Animation and App InitializationObject Oriented Assets OOP on CanvasDetect Mouse Coordinates on CanvasAnimated Background Layers on Canvas TutorialKeyboard Control and MovementJSON Object Arrays and Loops on CanvasHit Detection Mouse Touch Over Object ArraysCollision Detection Hit Game EnemiesParticle Effect System Tutorial Snow Falling AnimationInteractive Canvas Imaging Applications JavaScript PHP TutorialCircular Progress Loader Canvas JavaScript Programming Tutorial