Click an image, get coordinates

2020-08-25 05:48发布

问题:

I have a standard HTML image tag with an image in it, 100 by 100 pixels in size. I want people to be able to click the image and for that to pass the X and Y that they click into a function.

The coordinates need to be relative to the image top and left.

回答1:

I think you're talking about:

<input id="info" type="image">

When submitted, there are form values for the x and y coordinate based on the input element id (info.x and info.y in this case).

http://www.w3.org/TR/REC-html40/interact/forms.html#h-17.4.1



回答2:

from what you describe you should register to the image mouse event, for this case you should have the image mouse button event.

at the function you should use

Point mousePoint = e.GetPosition( this );

that will give you the mouse position according to the top left point int pixels.

than at the mousePoint you can print the X and Y information.



回答3:

Replace the canvas with your image and it will work the same

let img = document.getElementById("canvas");

img.x = img.getBoundingClientRect().left;
img.y = img.getBoundingClientRect().top;

function click(e) {
  document.getElementById("output").innerHTML = "X coords: " + (e.clientX - img.x) + "<br> Y coords: " + (e.clientY - img.y);
}

img.addEventListener("click", click);
<!--- Like a image --->
<canvas id="canvas" width="100" height="100"></canvas>
<p id="output"></p>