RaulS
RaulS

Reputation: 99

How to fit the size of the three.js renderer to a webpage element?

I need to fit the size of the renderer to the size of an element on the webpage. Doing renderer.setSize(window.innerWidth, window.innerHeight) sets the size of the renderer to fit the whole window.

init() {
      let map = document.getElementById('map');
      this.scene = new THREE.Scene();
      this.scene.background = new THREE.Color( 0xf0f0f0 );
      this.camera = new THREE.PerspectiveCamera(
        75,
        //window.innerWidth / window.innerHeight,
        1341/958, //hardcoded for now, but needs to be automatic
        0.1,
        1000,
      );
      this.camera.position.z = 3;
      this.renderer = new THREE.WebGLRenderer();
      //this.renderer.setSize(window.innerWidth, window.innerHeight); // it should not be a whole window
      this.renderer.setSize(1341,958); //hardcoded for now, but needs to be automatic
      map.appendChild(this.renderer.domElement);}

EXPECTED: if you uncomment the comments the whole renderer takes the size of the whole window.

ACTUAL: I had to hardcode the dimensions myself, but it is just a hotfix :(

Upvotes: 0

Views: 2939

Answers (1)

Davi
Davi

Reputation: 4147

You can get the dimensions of the element that contains your renderer (<canvas>) with getBoundingClientRect. Below is a little demo, showing the scaling of a <canvas> to the dimensions of a surrounding <div>:

var container = document.querySelector('#container');
var canvas = document.querySelector('#stage');

function scaleToFit (container, node) {
  var rect = container.getBoundingClientRect();
  node.width = rect.width;
  node.height = rect.height;
}

setTimeout(function () { scaleToFit(container, canvas); }, 1000);
#container {
  width: 100%;
  height: 500px;
}

#stage {
  background-color: #000;
}
<div id="container">
  <canvas id="stage" width="320" height="240"></canvas>
</div>

For your usecase, you can change your code like this:

init() {
      let map = document.getElementById('map');
      let mapDimensions = map.getBoundingClientRect();

      this.scene = new THREE.Scene();
      this.scene.background = new THREE.Color( 0xf0f0f0 );
      this.camera = new THREE.PerspectiveCamera(
        75,
        mapDimensions.width/mapDimensions.height,
        0.1,
        1000,
      );
      this.camera.position.z = 3;
      this.renderer = new THREE.WebGLRenderer();
      this.renderer.setSize(mapDimensions.width, mapDimensions.height);
      map.appendChild(this.renderer.domElement);}

Upvotes: 2

Related Questions