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?

neowenshun
  • 860
  • 1
  • 7
  • 21
  • 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? – blex Dec 20 '20 at 12:33
  • 3
    Does this answer your question? [get clicks through html canvas](https://stackoverflow.com/questions/3615533/get-clicks-through-html-canvas) – pilchard Dec 20 '20 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 – neowenshun Dec 20 '20 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](https://stackoverflow.com/questions/442404/retrieve-the-position-x-y-of-an-html-element-relative-to-the-browser-window) and compare it to the x,y click coordinates and [click the button programmatically](https://stackoverflow.com/questions/24278469/click-a-button-programmatically-js) – blex Dec 20 '20 at 12:38

1 Answers1

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

ATP
  • 2,939
  • 4
  • 13
  • 34
  • 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? – neowenshun Dec 20 '20 at 12:57
  • 1
    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 – neowenshun Dec 20 '20 at 13:05