How do I keep mesh centered no matter the width of the browser?

I have content that takes half the viewport, behind that content is a canvas that covers the entire page 100vh and 100vw . This is what it looks like with a small width, notice how the cube is centered, which is what I want.

image

But when I resize the window’s width, this is what happens, (I also show what I want in green).

If it helps, here are two sites that keep their meshes centered no matter the width of the page (for the second one you have to scroll down for a bit until the camera moves).

https://threejs-journey.com/ https://bokoko33.me/

Here’s my codepen: https://codepen.io/eddystream-7/pen/oNEPNpx?editors=1111

If it helps, I noticed that on both of the sites, their width and height on their canvas is twice as big as the style, not exactly what sure that means.
image

If the canvas is 100vw then 0/0 would be center of the screen, if you want it in the center of the second half then obj.x has to be viewport.width / 4 and this has to be refreshed on every resize.

Thank you for your answer, let’s say it’s my camera moving on x and z direction instead but my mesh remains at (0,0,0). What would I do differently? Currently my camera is what moved but my mesh remains at 0,0,0 and I’m using lookAt to look at 0,0,0

i don’t know, probably a lot of math. you have a viewport that consists of how many three units will fill the screen, you would normally use that to position objects or keep them responsive to resize.

if i had to do it: wizardly-mclean-j7fpqq - CodeSandbox

this is how you calculate viewport if i’m not mistaken:

let viewport
const { width, height } = size // canvas size in pixels
const distance = camera.getWorldPosition(position).distanceTo(new THREE.Vector3(0, 0, 0))
if (isOrthographicCamera(camera)) {
  viewport = { width: width / camera.zoom, height: height / camera.zoom }
} else {
  const fov = (camera.fov * Math.PI) / 180 // convert vertical fov to radians
  const h = 2 * Math.tan(fov / 2) * distance // visible height
  const w = h * (width / height)
  viewport = { width: w, height: h }
}

calculating camera to do the same would most likely be worse, but i don’t know.

No problem, and thank you for your help. That does seem incredibly complicated math, I don’t really understand any of it. Maybe I will just move my mesh instead until I get better at math.

welcome to threejs :smile:

1 Like

Ha, I actually contacted both of the creators of the sites and they responded, one of them just moved and changed the canvas size not the actual scene itself, and the other one did what you suggested, they never moved the camera, they just moved the object. Thank you again, I appreciate it.