Skip to content

Instantly share code, notes, and snippets.

@ayamflow
Last active December 13, 2024 12:38
Show Gist options
  • Save ayamflow/96a1f554c3f88eef2f9d0024fc42940f to your computer and use it in GitHub Desktop.
Save ayamflow/96a1f554c3f88eef2f9d0024fc42940f to your computer and use it in GitHub Desktop.
Threejs Fit plane to screen
var cameraZ = camera.position.z;
var planeZ = 5;
var distance = cameraZ - planeZ;
var aspect = viewWidth / viewHeight;
var vFov = camera.fov * Math.PI / 180;
var planeHeightAtDistance = 2 * Math.tan(vFov / 2) * distance;
var planeWidthAtDistance = planeHeightAtDistance * aspect;
// or
let dist = camera.position.z - mesh.position.z;
let height = ... // desired height to fit
camera.fov = 2 * Math.atan(height / (2 * dist)) * (180 / Math.PI);
camera.updateProjectionMatrix();
// Basically solving an AAS triangle https://www.mathsisfun.com/algebra/trig-solving-aas-triangles.html
https://i.stack.imgur.com/PgSn3.jpg
@thibka
Copy link

thibka commented Aug 23, 2020

Thanks!

@jadepark-dev
Copy link

Great, thank you!

@mikatalk
Copy link

Excellent, merci! 🌟

@manudurgoni
Copy link

Merci chouchou <3

@julapy
Copy link

julapy commented Dec 23, 2022

here is another approach, changing the position and rotation of the plane to always fit the screen.

  const fitPlaneToScreen = (planeMesh, planeHeight) => {
    let aspect = window.innerHeight / window.innerWidth;
    if( aspect < 1.0 ) {
      planeHeight *= aspect;
    }
    let distance = planeHeight * 0.5 / Math.tan( camera.fov * 0.5 * (Math.PI/180) );
    let cameraDir = new THREE.Vector3();
    camera.getWorldDirection( cameraDir );
    planeMesh.position.set( camera.position.x, camera.position.y, camera.position.z );
    planeMesh.position.add( cameraDir.multiplyScalar( distance ) );
    planeMesh.rotation.setFromRotationMatrix( camera.matrix );
  }

pass in the plane mesh and the height of the plane mesh geometry when it was created.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment