I’ve been trying to create a function that can convert pixels to units so that i can put 3D objects in a layer under a html page. I need this so that i can have the camera position.y linked with the page scroll y. 3d objects need to be placeable at exact pixel position and sizes of html objects. These html objects change size on resize so the objects will need to check the html object size and resize and reposition accordingly.
What would be the best way to do this in BabylonJS? I have tried the following:
create a box of 10, resize box to fit view, divide box size by screen size: now we know how much units 1 pixel is. This gives sort of what i need, but does not work well when the aspect ratio goes above 1.5.
cam = new UniversalCamera(
new Vector3(0, 0, 50),
cam.setTarget(new Vector3(0, 0, 0));
cam.fovMode = 0; // FOVMODE_VERTICAL_FIXED
cam.fov = Math.radians(45);
cam.minZ = 0.1;
cam.maxZ = 10000;
const cardMesh = BoxBuilder.CreateBox(
const size = cardMesh.getBoundingInfo().boundingBox.extendSizeWorld;
const maxSize = size.x;
const ratio = engine.getAspectRatio(cam);
const h = maxSize / (Math.tan(cam.fov / 2) * ratio);
cam.position.z = h;
Does anyone know how this could be done better with more precision?
I think it might be related to the way Babylon scales the content when resizing the canvas. Is there a way to link this to canvas size like you can in three js, like in this example?
- camera.aspect = canvas.clientWidth / canvas.clientHeight;
I know you can set fov fixed vertical or horizontal but i think i need both fixed.