Reputation: 23
I want to create a series of interactive areas in a canvas. The number of areas are dynamic so I cannot hardcode the coordinates.
Im adding the areas to a click event handler like this...
$('#FootprintCV').click(function (e) {
var clickedX = e.pageX - this.offsetLeft;
var clickedY = e.pageY - this.offsetTop;
if (clickedX < area1.right && clickedX > area1.left && clickedY > area1.top && clickedY < area1.bottom) {
console.log('Area1 clicked at X: ' + clickedX + " Y:" + clickedY);
}
}
});
Upvotes: 1
Views: 52
Reputation: 696
I suggest you add objects to an array and iterate on the array whenever a click occurs...
Create an array and objects containing coordinates for your areas
var clickShapes = [];
clickShapes.push(shapeObject1);
clickShapes.push(shapeObject2);
clickShapes.push(shapeObject3);
When the click is picked up, iterate on the array to catch the event.
$('#FootprintCV').click(function (e) {
var clickedX = e.pageX - this.offsetLeft;
var clickedY = e.pageY - this.offsetTop;
var i = clickShapes.length;
while (i-- && i >= 0) {
if (clickedX < clickShapes[i].right && clickedX > clickShapes[i].left && clickedY > clickShapes[i].top && clickedY < clickShapes[i].bottom) {
console.log('Circle nr ' + i + ' clicked at X: ' + clickedX + " Y:" + clickedY);
}
}
});
Upvotes: 2