Question

A couple of questions in my head while studying Interaction with Three.js

1)Please explain what are Viewport Coordinates?

2)How they differ from client Coordinates?

3)How we ran onto this formula.

var vpx = ( eltx / div.offsetWidth ) * 2 - 1;
var vpy = - ( elty / div.offsetHeight ) * 2 + 1;
// vp->viewport, eltx->client coords,div->The div where webGL renderer has been appended.

4)Why we take 3rd coordinate in viewport System as 0.5 to 1 while taking the vector ?

I would be really grateful if you will explain these Questions and the concept in detail or suggest me a book to read from. Best if some 3D diagrams are available for 1st Question. Would be really really thankful.

Était-ce utile?

La solution

The 3D Scene is rendered inside a canvas container. It can be any size, and located anywhere in the layout of a HTML page. Very often WebGL examples and apps are made made full screen, so that the canvas fills the whole screen and is effectively the same size as the HTML layout. But that's not always the case, and a WebGL scene can be embedded alongside other HTML content, much like an image.

Three.js generally doesn't care or know about how the 3D canvas relates to the coordinates and size of the whole HTML page. Inside the WebGL canvas a completely different coordinate system -totally independent of screen pixels- is used.

When you want to handle clicks inside the 3D canvas, unfortunately the browser only gives the pixel values counting from the top left corner of the HTML page (eltx and elty). So you need to first convert the HTML mouse coordinates to the WebGL coordinates (a vector usable in Three.js). In WebGL coordinates, 0,0 is the center of canvas, -1,-1 is top left, +1,+1 bottom right and so on, no matter what the size and position of the canvas is.

First you need to take the position of the canvas and subtract that from the mouse coordinates. Your formula does not take that into account, but instead assumes that the webgl container is located at the top left corner of the page (canvas position is 0px 0px). Thats ok but if you the container is moved or the HTML body has CSS padding for example, it won't be accurate anymore.

Second you need to convert the absolute mouse pixel position (adjusted in the previous step), and convert that to relative position inside the canvas. That's what your formula does. If mouse x position is 50px and your canvas is 100px wide, the formula goes like (50/100) * 2 - 1 = 0, which is the screen space center of the canvas viewport.

Now you have coordinates that make sense in the Three.js 3D scene.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top