Convert 3D Three.js world coordinates to 2D screen positions for UI overlays
View the Demo page and open the browser console.
Vector3
x: 960
y: 540
z: 0
threejs-position-util converts a 3D geometry position to 2D screen coordinates (CSS pixels; origin at top-left), ideal for positioning HTML UI elements over 3D objects.
npm install @masatomakino/threejs-position-util --save-dev
Import the named exports from the package root:
import {
get2DPosition,
get2DPositionWithMesh,
getGeometryCenterInWorld,
getGeometryCenterInLocal
} from "@masatomakino/threejs-position-util";
This package is ESM-only; CommonJS require() is not supported.
The main purpose of this library is to convert 3D positions to 2D screen coordinates:
get2DPositionWithMesh(mesh, camera, canvasW, canvasH)
Convert a mesh's center position directly to 2D screen coordinates. This is the most commonly used function for positioning UI elements over 3D objects.
const screenPos = get2DPositionWithMesh(myMesh, camera, 1920, 1080);
// Position an HTML element at the mesh location
htmlElement.style.left = `${screenPos.x}px`;
htmlElement.style.top = `${screenPos.y}px`;
get2DPosition(vec3, camera, canvasW, canvasH)
Convert any 3D world position to 2D screen coordinates.
const worldPosition = new THREE.Vector3(10, 5, -20);
const screenPos = get2DPosition(worldPosition, camera, 1920, 1080);
// Get mesh center in world coordinates
const worldCenter = getGeometryCenterInWorld(mesh);
// Get mesh center in local coordinates
const localCenter = getGeometryCenterInLocal(mesh);
All functions return a position as THREE.Vector3
.