StillLearning StillLearning - 10 months ago 65
Javascript Question

Make mouse coordinates relative to <canvas> coordinates

I am trying to find where the mouse is on a canvas's 'grid' while maintaining resizability. I currently have the mouse coordinates for where it is on the screen (x and y).

The problem is, the 'scaling' between WebGL (which I am using to draw on the canvas) and the mouse coordinates is different. What WebGL considers to be 10 units to the right from origin is actually considered x number of units from the origin (different screen resolution changes this). This means that when my mouse is over what WebGL considers (10, 10), my mouse coordinates are (100, 100).

How would I convert the mouse coordinates on the screen to the 'WebGL coordinates' which are used to define a point?

This is similar to this question but I would like to do it without using Fabric.js.

Answer Source

To convert canvas mouse coordinates to relative coordinates in the range of -1 to +1, one first needs to get the relative pixel coordinates within the canvas using offsetX/offsetY provided by the mouse event.

Then divide this by the actual width and height of the canvas using clientWidth/clientHeight.

Having the relative coordinates in a range from 0 to 1 we can now move them into the right range by multiplying by 2 and subtracting 1.

Note that in WebGL the up axis is positive 1 so one wants to invert the Y coordinate.

All put together:

var ndcX = (mouseEvent.offsetX / canvas.clientWidth) * 2 - 1;
var ndcY = (1 - (mouseEvent.offsetY / canvas.clientHeight)) * 2 - 1;