'Get X, Y position in canvas

In JS, we could use Element.getBoundingClientRect() to get element's X and Y coordinates. But what if we want to know the X,Y coordinates of an element in canvas

The closet thing I could think about is CanvasRenderingContext2D.isPointInPath() to check without a point exists in the shape. Is there a built-in function or any way to get X and Y coordinates of a shape in canvas?

For example,

const canvas = document.querySelector('canvas');
const ctx = canvas.getContext('2d');

ctx.rect(10, 10, 100, 100);
ctx.fill();
canvas{
width:200px;
height:200px;
background:red;
}
<canvas></canvas>
Is there a way I get the top/left coordiates of the black rect?

Any answers will be appreicated.



Solution 1:[1]

The coordinates you use to specify the rect begin with the x/y pair for the top-left corner of the rect relative to the canvas.

One would expect the screen coordinates to be obtained by adding the rect's x value to the canvas.getBoundingClientRect().left value for the screen x coordinate, and the y value added to the canvas.getBoundingClientRect().top value would give the y coordinate.

If you are adding shapes to the rect using js, it would be relatively easy to keep track of the top left of each in variables and calculate screen coordinates as you go.

as a rough and ready means of (manually) obtaining a reasonable estimate of any point, a simple click eventListener could be used to report coordinates of points you click on:

const canvas = document.querySelector('canvas');
const ctx = canvas.getContext('2d');
ctx.rect(10, 10, 100, 100);
ctx.fill();

canvas.addEventListener ('click', event => {
  console.log(`x: ${event.screenX}, y: ${event.screenY}`)
})
<canvas width="200px" height="200px" style="background:red"></canvas>

Solution 2:[2]

I think it's quite simple. Where you make you're box like this; ctx.rect(10, 10, 100, 100);, Instead do this;

var x = 10;
var y = 10;

ctx.rect(x, y, 100, 100);

Then you can move it however you like and know where it is, e.g. document.getElementById("demo").innerHTML = "x:" + x + "y:" + y; at the end of your code and then put <p id="demo"></p> in the html part. If you want to it to update in real-time try using requestAnimationFrame, but try to put it in a function first.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2 octoCat