1

Basically, I wish to overlay a canvas over some HTML but still be able to click elements below, say a button or a link

I am able to get the x-y coordinate of the click on the canvas. Is there a way to trigger the button click below programmatically with the x-y coordinate?

4
  • Out of curiosity: is a button even necessary at all? Can't you just execute the function directly when the canvas is clicked within specific coordinates? Commented Dec 20, 2020 at 12:33
  • 3
    Does this answer your question? get clicks through html canvas Commented Dec 20, 2020 at 12:36
  • I guess that's true, however ideally I would want to dynamically propagate the click through, without having to respecify the 'clickable' area whenever there's a new button or the button shift Commented Dec 20, 2020 at 12:36
  • Then, if you don't need to detect cursor events on the canvas, use pilchard's proposed duplicate (canvas { pointer-events: none; } in the CSS). Otherwise, you'll need to retrieve the position of the button and compare it to the x,y click coordinates and click the button programmatically Commented Dec 20, 2020 at 12:38

1 Answer 1

4

Try this:

document.elementFromPoint(x, y).dispatchEvent(new MouseEvent("click", {bubbles: true}));

document.elementFromPoint(50, 50).dispatchEvent(new MouseEvent("click", {bubbles: true}));
div{
  height:100px;
  width:100px;
  background:red;
  
}
<div onclick="alert('clicked')">

</div>

thanks to this answer and this srticle

Sign up to request clarification or add additional context in comments.

2 Comments

Hey! thanks for the response, this was what i was looking for, i realize that it returned the canvas that was ontop, instead of the button thats below the canvas is there a way to fix it?
Alright solved! I used elementsFromPoint instead of elementFromPoint, it returned a list, the only sketchy part is that the way i did it was to access the element im looking for , in this case the second element

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.