0

I have a basic canvas

<body>
    <canvas id="Canvas" width="500" height="704" style="border:1px solid #000000;"> </canvas>
</body>

and I'm trying to get the coordinates of onClick event inside of the canvas. I found a good post about doing it with event.offsetX (referenced post) however, that code only works when the js script is in the same file. What I'd like to do is handle the coordinates in a function that's in a separate "app.js" file. I tried referencing the function that I'd like to handle the data (let's call it "click()" ) in the onClick property of the canvas. I'm not sure if that's the wrong aproach or I missed something but it didn't work. I'm just strating out with javascript. Ideally I'd like to have no javascript in the html file at all but I'll be happy with whatever works.

Thanks

ThatMatt
  • 5
  • 3
  • You must be doing something wrong on that JS file... it should work in the same file or external, can you add entire code of your project – Helder Sepulveda Mar 26 '20 at 01:20

1 Answers1

0

this is for the global click on the element but it still captures the position of the click inside the canvas :

let ctx = mycanvas.getContext("2d");
if(ctx) mycanvas.addEventListener("click",event =>{console.log(event.offsetX);});
<canvas id="mycanvas" height="500" width="500"></canvas>
codeanjero
  • 674
  • 1
  • 6
  • 14