Click here to Skip to main content
15,887,214 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I'm trying to build a knockoff of r/Place, and I've got quite a bit done. But what I'm stuck on is how I can get the coordinates of a mouse click in a canvas element that can be scaled up or down.

What I have tried:

I've tried this code from geeksforgeeks.org but it changes the coordinates completely when you zoom in or out:
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);
});


I was also thinking of making a huge <map> element, but with a 250x250 grid that I might turn into something like 500x500 (or more) later, I don't think that's a good solution.

Edit: canvas scaling is handled by a scrollwheel event and the transform: scale() CSS attribute
Posted
Updated 9-Jun-23 5:49am
v2

1 solution

You can make use of the 'devicePixelRatio property' which should solve your issue when a user zoom their page - Window: devicePixelRatio property[^]

I made a fiddle that seems to work irrespective of zoom percentage - [^]

I used the code inside the body element with 'document.onclick' to call the function also inside the body element -
<html>
<head>
  <title>Mouse Click Position</title>
  
</head>
<body>
<p>
Hi
</p>
<script>
    function getMousePosition(event) {
      const zoomLevel = window.devicePixelRatio || 1; // Get the zoom level of the page

      let x = event.clientX / zoomLevel; // Adjust the X coordinate by the zoom level
      let y = event.clientY / zoomLevel; // Adjust the Y coordinate by the zoom level

      alert("Mouse Click Position - X: " + x + ", Y: " + y);
    }

    document.onclick = getMousePosition;
  </script>
</body>
</html>
 
Share this answer
 
v2
Comments
A-Games 9-Jun-23 11:51am    
I modified your code a bit so it'd work with my method of scaling the canvas (that is now in the question) and it still has the scaling issues. Less scaling issues, but they're still there.
Andre Oosthuizen 10-Jun-23 5:00am    
You need to be more precise in what is happening, remember, I cannot see your screen. The above worked fine as per my jsfiddle.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900