2

So I am trying to create a 2d drawing program in WebGL and I can draw everything fine but I am having a lot of difficulty detecting the location of mouse clicks.

I have a 4x4 projection matrix set up as follows:

mat4.perspective(45, this.gl.viewportWidth / this.gl.viewportHeight, 0.1, 100.0, projectionMatrix);

I then have a 4x4 view matrix which holds the camera position as follows:

mat4.translate(viewMatrix, [camera.getX(), camera.getY(), camera.getZoom()]);

I can get a 2d vector of the position of the mouse click on the screen ranging from [-1,-1] in the top left to [1,1] in the bottom right.

What I want to be able to do is take the current position of the camera, get the frustum bounds on the z-plane and then use my relative mouse click positions to get the actual world space position on the z-plane.

Note:

  • The camera does not rotate, only pan and zoom.
  • Everything is drawn on the model matrix which is on the z=0 plane.

see image here

StephenKing
  • 36,187
  • 11
  • 83
  • 112
AndyM
  • 151
  • 1
  • 5
  • Then why do you use a perspective projection matrix at all? Anyway, have you looked at general unprojection? Basically, you want to multiply the mouse coordinates with the inverse view-projection matrix. – Nico Schertler Aug 10 '16 at 22:45
  • I want to use a projection matrix in order to zoom in and out. Is there an alternative? – AndyM Aug 10 '16 at 23:01
  • Yes, use an orthographic projection matrix. But the unprojection procedure is the same for both (although you would need a reasonable depth for the perspective matrix). – Nico Schertler Aug 10 '16 at 23:06
  • Is something like http://stackoverflow.com/questions/35583808/3d-math-screen-space-to-world-space/35590403#35590403 what you are looking for? – WacławJasper Aug 11 '16 at 05:51
  • You might find [these articles useful](http://webglfundamentals.org/webgl/lessons/webgl-2d-matrix-stack.html). Panning and zooming can be thought of as just prepending a translation and scale matrix to your stack. – gman Aug 15 '16 at 04:53

0 Answers0