user3055938 user3055938 - 7 months ago 28
Javascript Question

Create a click event in the middle of a element/canvas element?

I've seen and used code that allows you to create a click event on a element, but it seems these click events are created at the 0,0 coordinates of the element. I have a canvas element that I need a click event created for near the center of it.

How can I create a click event near the center of an element?

For example say I wanted to click on the spot at 20px,30px of this element:

<canvas style="width: 50px; height: 50px;">

I've tried setting the mouse event properties clientX and clientY, but that didn't register the click where it should've so I guess those properties don't do what I thought they did.


Just by checking the documentation for MouseEvent on MDN, you could try the following. I did not see a way to select the pixels in the element itself, but you could calculate the position you want on the window using the results of the getBoundingClientRect method on your canvas element.

var canvasBCR = canvas.getBoundingClientRect();
canvas.dispatchEvent(new MouseEvent("click", {clientX: canvasBCR.left + 20, clientY: + 30}));