Rich-Harris/svelte-cubed

projection

Opened this issue · 1 comments

given an object, what are its projected x,y coordinates?

In my project, I'm projecting object coordinates to viewport coordinates in an Html component akin to the one from @react-three/drei. Not sure what other use cases there are for projecting points (perhaps a method exposed though context or something could work for those?), but a Html component seems like a good start. I'd be happy to put together a PR for that if it sounds alright.

The core logic for it isn't very advanced. It basically comes down to:

const projectedPosition = new Vector3();
projectedPosition.set(...position);
projectedPosition.project(camera);

const canvas = renderer.domElement;
const canvasHalfWidth = canvas.width / 2;
const canvasHalfHeight = canvas.height / 2;

projectedPosition.x = projectedPosition.x * canvasHalfWidth + canvasHalfWidth;
projectedPosition.y = -(projectedPosition.y * canvasHalfHeight) + canvasHalfHeight;

Edit: I suppose my case is a bit simplified since I only bother to deal with world coordinates here, but translating an arbitrary object's local coordinates to world coordinates first should be fairly trivial.