Pixel Perfection with Three.js

June 18th, 2013

I've had the chance to spend a couple weeks messing with WebGL for work. Three.js is an invaluable library if you haven't used it. But one of the most important things I've learned using it, is the equation to set the camera's distance from an object so that the object's dimensions are pixel perfect. There is a similar equation in Flash when working with Away3D or Papervision3D.

camera's z = viewport's height / (2 * tan(vertical FOV / 2) )

or in javascript:

var fov = 45;
var vFOV = fov * (Math.PI / 180); // convert to radians
camera.position.z = vpHeight / (2 * Math.tan(vFOV / 2) );

And if your object is offset from the z-axis then you add that distance to the camera position.