Hosting Solutions
mobile_logo Table of Contents
seal_frontseal_back

Hit Detection Mouse Touch Over Object Arrays

Learn mouse or touch hit detection against an array of objects on the HTML canvas using JavaScript. <!DOCTYPE html> <html> <head> <style> body{ background:#CCC; } #my_canvas{ background:#FFF; border:#999 1px solid; } </style> <script> function initCanvas(){ var ctx = document.getElementById('my_canvas').getContext('2d'); ctx.canvas.addEventListener('mousedown', function(event) { var mX = event.clientX - ctx.canvas.offsetLeft; var mY = event.clientY - ctx.canvas.offsetTop; for(var i = 0; i < buildings.length; i++){ var b = buildings[i]; if(mX >= b.x && mX < b.x+b.w && mY >= b.y && mY < b.y+b.h){ document.getElementById('status').innerHTML = "You touched "+b.id; } } }); 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> <h2 id="status"></h2> </body> </html>
thumb

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