<body>
  <div id="canvas"></div>
</body>
body {
  margin: 0;
  padding: 0;
  background: #012345;
  //overflow: hidden;
}

#canvas {
  position: absolute;
}

#testing {
  color: red;
  font-family: arial;
  position: absolute;
  top: 100px;
}
const scene = new THREE.Scene();
const camera = new THREE.PerspectiveCamera(45, window.innerWidth / window.innerHeight, 1, 10000);




let renderer = new THREE.WebGLRenderer();
renderer.setSize( window.innerWidth, window.innerHeight );
renderer.setClearColor(0xFFFCFF);

document.getElementById("canvas").appendChild(renderer.domElement);

window.addEventListener('resize', function () {
     let width = window.innerWidth;
     let height = window.innerHeight;
     renderer.setSize(width,height);
     camera.aspect = width / height;
     camera.updateProjectionMatrix();
});



const visibleHeightAtZDepth = (depth, camera) => {
     // vertical fov in radians
     const vFOV = camera.fov * Math.PI / 180;

     // Math.abs to ensure the result is always positive
     return 2 * Math.tan(vFOV / 2) * Math.abs(depth);
};




var mesh, controls;


     var screenDepth;
     screenDepth = findScreenDepth(camera, renderer)

     const redGeom =  new THREE.BoxGeometry( 5,5,5 );
     const redMat = new  THREE.MeshNormalMaterial({wireframe: true});
     const redMesh = new THREE.Mesh(redGeom, redMat);
     redMesh.position.set(0 /*px*/, 0, -screenDepth + 20);
     redMesh.scale.set(5,5,5)
     scene.add(redMesh, camera);



function findScreenDepth(camera, renderer) {
     const { near, far } = camera;
     const { height: physicalViewHeight } = renderer.getDrawingBufferSize();
     console.log(window.innerHeight, physicalViewHeight);
     const threshold = 0.00000000000001;

     return _findScreenDepth(near, far);

     function _findScreenDepth(near, far) {

          const midpoint = (far - near) / 2 + near;
          const midpointHeight = visibleHeightAtZDepth(-midpoint, camera);

          if (Math.abs(physicalViewHeight / midpointHeight - 1) <= threshold)
               return midpoint;

          if (physicalViewHeight < midpointHeight)
               return _findScreenDepth(near, midpoint);else
          if (physicalViewHeight > midpointHeight)
               return _findScreenDepth(midpoint, far);else
          if (midpointHeight == physicalViewHeight) // almost never happens
               return midpoint;
     }
}
camera.position.z = 20;
let ADD = 3.5;
function animate() {
     requestAnimationFrame(animate);
     redMesh.position.x += ADD;
     if (redMesh.position.x <= (-window.innerWidth/2)+20|| redMesh.position.x >= (window.innerWidth/2)-20) {
          ADD *= -1;
     }
     renderer.render(scene, camera);

}
animate();
Run Pen

External CSS

This Pen doesn't use any external CSS resources.

External JavaScript

  1. https://cdnjs.cloudflare.com/ajax/libs/three.js/r122/three.min.js