Sunday, 23 May 2021

How to fit object inside canvas in three js

I'm currently using threejs library to create 3d objects, but unfortunately I cannot fit the object inside the canvas. It's always overflowing outside the canvas if the object is a bit long. Please see my code below.

JSFiddle Code

JS Code

import * as THREE from 'https://threejsfundamentals.org/threejs/resources/threejs/r127/build/three.module.js';

function main() {
  const canvas = document.querySelector('.square');
  const renderer = new THREE.WebGLRenderer({ canvas });
  const canvasWidth = canvas.getBoundingClientRect().width;
  const canvasHeight = canvas.getBoundingClientRect().height;
  
  // renderer.setPixelRatio( canvas.devicePixelRatio )
  // renderer.setSize(canvasWidth, canvasHeight)
  renderer.antialias = true
  
  const fov = canvasWidth; //75;
  const aspect = canvas.clientWidth / canvas.clientHeight;
  const near = 0.1;
  const far = 5;
  const camera = new THREE.PerspectiveCamera(fov, aspect, near, far);
  camera.position.z = 2;

  const scene = new THREE.Scene();
  scene.background = new THREE.Color(0xe0e0e0)

  {
    const color = 0xFFFFFF;
    const intensity = 1;
    const light = new THREE.DirectionalLight(color, intensity);
    light.position.set(-1, 2, 4);
    scene.add(light);
  }

  const boxWidth = 5;
  const boxHeight = 1;
  const boxDepth = 1;
  const geometry = new THREE.BoxGeometry(boxWidth, boxHeight, boxDepth);

  const material = new THREE.MeshPhongMaterial({ color: 0x44aa88 });  // greenish blue

  const cube = new THREE.Mesh(geometry, material);
  scene.add(cube);

  function render(time) {
    //time *= 0.001;  // convert time to seconds

    cube.rotation.x = 3.6;
    cube.rotation.y = 3.9;

    renderer.render(scene, camera);

    requestAnimationFrame(render);
  }
  
  requestAnimationFrame(render);

}

main();



from How to fit object inside canvas in three js

No comments:

Post a Comment