Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

getBoundingClientRect is not a function

I am trying to get the coordinates of the mouse-click on a image. So I'm using getBoundingClientRect like this

function showCoords(canvas, event) {
    var rect = canvas.getBoundingClientRect();
    var x = event.clientX - rect.left;
    var y = event.clientY - rect.top;
    console.log("x: " + x + " y: " + y);
}

But I get this error "canvas.getBoundingClientRect is not a function"

like image 391
Sam Avatar asked Jan 16 '18 21:01

Sam


People also ask

What is getBoundingClientRect () in Javascript?

The getBoundingClientRect() method returns the size of an element and its position relative to the viewport. The getBoundingClientRect() method returns a DOMRect object with eight properties: left, top, right, bottom, x, y, width, height.

What is getBoundingClientRect in react?

getBoundingClientRect() method returns a DOMRect object providing information about the size of an element and its position relative to the viewport.

Does getBoundingClientRect include padding?

Border, padding and margin are not included.


1 Answers

That means that canvas variable is not actually a Canvas element.

It can be undefined, still not initialized or incorrectly selected.

You need to double check it and maybe try to use event.target if the click event is added to the canvas element.

like image 58
Sergii Rudenko Avatar answered Oct 02 '22 11:10

Sergii Rudenko