I’m trying to display 3D in 2D HTML canvas making use of Three.js. I can calculate the 2D screen coordinate of a 3D point with:
function project(vector, camera, width, height){
const v = vector.clone().project(camera);
return new Vector2(Math.round((v.x + 1) * width / 2), Math.round((-v.y + 1) * height / 2));
}
I want to draw a circle with a radius of 1 world unit at that point and work out what it would be in pixels. I could project another point that is 1 world unit away. Another method is to use trigonometry:
function projectionScale(fieldOfView, distanceFromCameraInWorldUnits, heightInPx) {
const focalLength = (heightInPx / 2) / Math.tan(fieldOfView / 2);
if (distanceFromCameraInWorldUnits === 0) {
return heightInPx / 2;
} else {
return (focalLength * 64) / distanceFromCameraInWorldUnits;
}
}
I’m having to make use of an arbitrary constant 64 so it comes close to the first method so there is something wrong with it.