Ask coding questions

← Back to all posts
Real mouse coords on canvas
realTronsi (913)

I'm using a simple script to get the "real" mouse position on a canvas with a cameraX, cameraY, and cameraZ representing the scale/zoom. The mouse coordinates become inaccurate once you apply a zoom and translate, where it starts tending towards the direction of translation. I'm sure it's a simple fix that I'm not seeing. Any help?

//getting mouse coords
canvas.addEventListener("mousemove", e => {
  mouseX = (e.clientX - canvas.getBoundingClientRect().left) / cameraZ;
  mouseY = (e.clientY - canvas.getBoundingClientRect().top) / cameraZ;

  mouseX += cameraX - (canvas.width / 2) / cameraZ;
  mouseY += cameraY - (canvas.height / 2) / cameraZ;
ctx.translate(-cameraX + canvas.width/2, -cameraY + canvas.height/2);
ctx.scale(cameraZ, cameraZ);