1

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);
        }
    }
});

1 Answer 1

2

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);
        }
    }
});
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.