âš ī¸ Warning âš ī¸ Deprecated Code! This video tutorial contains outdated code.
💡 If you wish to update it, any AI assistant will update the code for you in seconds.

Hit Detection Mouse Touch Over Object Arrays

Published : November 17, 2014   •   Last Edited : November 24, 2025   •   Author : Adam Khoury
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;
            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;
        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>