zearthur99
zearthur99

Reputation: 111

Get click the actual click location in canvas after a css resizing

First of all, let's suppose that I have the following canvas: <canvas id="can" width="400" height="200" />. And Then, I need to resize it with width: 100%; height: auto; to fit my responsive container. And now, let's suppose that my canvas got a width of 800. And the problem is that everytime when I try the get the position(x, y) of a click event, I get the coordinates relative to the actual mouse position.

To be clear, If I click the bottom-edge of the canvas, Insted of getting the position(400, 200), I get (800, 400).

Already searched on the web for a solution but I can't find my specific problem and neither jQuery or vanilla javascript seems to have a easy approach to the problem. The only solution that I thought of was using a kind of a mathematical relation between the actual canvas dimensions setted in the DOM and the width and height of it after the scaling, but I really can't figure how.

Upvotes: 2

Views: 1821

Answers (2)

psygo
psygo

Reputation: 7583

I think this answer by @patriques is really helpful:

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

const canvas = document.querySelector('canvas')
canvas.addEventListener('mousedown', function(e) {
    getCursorPosition(canvas, e)
})

Upvotes: 0

Nadir Muzaffar
Nadir Muzaffar

Reputation: 4842

One approach is to use offsetLeft and offsetTop property on your canvas element to transform the mouse coordinates to your canvas. It would work something like this:

function(clickEvent) {
   var canvas = document.getElementById("can")
   var transformedClickX = clickEvent.pageX - canvas.offsetLeft;
   var transformedClickY = clickEvent.pageY - canvas.offsetTop;

   ...
}

Upvotes: 1

Related Questions