<!DOCTYPE html>
<
html
>
<
head
>
<
title
>
How to get the coordinates of a mouse
click on a canvas element?
</
title
>
</
head
>
<
body
>
<
h1
style
=
"color: green"
>
GeeksforGeeks
</
h1
>
<
b
>
How do I get the coordinates of a
mouse click on a canvas element?
</
b
>
<
p
>
Click anywhere on the canvas element
to get the mouse pointer location.
</
p
>
<
p
>
The size of the canvas
is a square of 200px.
</
p
>
<
p
>Check the console for the output.</
p
>
<
canvas
width
=
"200"
height
=
"200"
style
=
"background-color: green"
>
</
canvas
>
<
script
type
=
"text/javascript"
>
function getMousePosition(canvas, event) {
let rect = canvas.getBoundingClientRect();
let x = event.clientX - rect.left;
let y = event.clientY - rect.top;
console.log("Coordinate x: " + x,
"Coordinate y: " + y);
}
let canvasElem = document.querySelector("canvas");
canvasElem.addEventListener("mousedown", function (e) {
getMousePosition(canvasElem, e);
});
</
script
>
</
body
>
</
html
>