Collision detection

Detection mouse-click hits on an HTML Canvas drawn object

by digory

HTML

<canvas id="board" width="150" height="150"></canvas>

CSS

canvas { border: 1px solid black; }

JavaScript

function Item(left, top, width, height) {
    this.Left = left;
    this.Top = top;
    this.Width = width;
    this.Height = height;
}

var items = [];

for (var i = 0; i <= 150; i += 15) {
    var item = new Item(i, i, 5, 5);
    items.push(item);
    Draw(item);
};

$('#board').click(function (e) {
    var x = e.pageX - this.offsetLeft;
    var y = e.pageY - this.offsetTop;
    var clicked = new Item(x, y, 1, 1);
    var pos = getPositions(clicked);
    
    for (var i = 0; i < items.length; i++) {
        var pos2 = getPositions(items[i]);
        var horizontalMatch = comparePositions(pos[0], pos2[0]);
        var verticalMatch = comparePositions(pos[1], pos2[1]);
        if (horizontalMatch && verticalMatch) {
            console.log(pos2);
        }
    }
});

function Draw(item) {
    var canvas = document.getElementById('board');
    if (canvas.getContext) {
        var ctx = canvas.getContext('2d');
        ctx.fillRect(item.Left, item.Top, item.Width, item.Height); // x, y, width, height
    }
}

// http://vidasp.net/tinydemos/javascript-detect-overlapping.html
function getPositions(item) {
    return [[item.Left, item.Left + item.Width], [item.Top, item.Top + item.Height]];
}

function comparePositions(p1, p2) {
    var x1 = p1[0] < p2[0] ? p1 : p2;
    var x2 = p1[0] < p2[0] ? p2 : p1;
    return x1[1] > x2[0] || x1[0] === x2[0] ? true : false;
}