# Position a mesh to follow DOM element's position

Hello everyone, I’m trying to write a program to fit a mesh into a DOM element’s bounds. I firstly use the orthographic camera mode so its perspective is closer to a 2D one.

I searched the calculation of how to calculate bounds from 3D space to 2D pixels, so I make use of this to work out how to calculate the mesh position, like this:

• Find current mesh bounds in pixels
• Find current mesh bounds in vector3
• Find out the x/y differences in pixels the mesh need to move
• New mesh position x = current mesh position x + x difference * (mesh width in vector3) / (mesh width in vector3)

Place mesh within bounds of DOM element | Babylon.js Playground (babylonjs.com)

I can get the x position calculated correctly, but for y, it seems to be negative so I negate it, but the result is still incorrect. Can anyone advice on how to correctly calculate the new position y of the mesh? Thank you very much!

Welcome to the forums!

Hmm, I’m not sure how easy this will be. Maybe @Evgeni_Popov has some ideas?

Thanks Gary! I managed to find out this solution:

The idea is move a sample distance in 3d space and see how much moved in 2d:

var sampleFactor = 0.1;

``````    var oldX = meshBounds.x;
var oldY = meshBounds.y;

sphere.position.x += sampleFactor;
sphere.position.y += sampleFactor;

scene.render();

var meshBoundsAfterMovedSampleFactor = getBoundsForMesh(sphere);

var newX = meshBoundsAfterMovedSampleFactor.x;
var newY = meshBoundsAfterMovedSampleFactor.y;

var xRatio = sampleFactor / (newX - oldX);
var yRatio = sampleFactor / (newY - oldY);

sphere.position.x += xDiff * xRatio;
sphere.position.y += yDiff * yRatio;
``````

It kind of works but I also hoping for a more formal way to achieve the same goal. Thanks.

You can do it by unprojecting the center of your rectangle and use this point as the sphere position:

4 Likes

Wow Evgeni, thank you very much, and so happy that I learn something new!