【问题标题】:How to fit the size of the three.js renderer to a webpage element?如何使three.js 渲染器的大小适合网页元素?
【发布时间】:2019-01-16 00:09:16
【问题描述】:

我需要使渲染器的大小适合网页上元素的大小。执行renderer.setSize(window.innerWidth, window.innerHeight) 将渲染器的大小设置为适合整个窗口。

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);}

预期:如果您取消注释 cmets,整个渲染器将占用整个窗口的大小。

实际:我必须自己对尺寸进行硬编码,但这只是一个修补程序:(

【问题讨论】:

  • map.style.height 和 map.style.width 应该返回您需要的尺寸

标签: javascript html three.js


【解决方案1】:

您可以使用getBoundingClientRect 获取包含您的渲染器 (<canvas>) 的元素的尺寸。下面是一个小演示,展示了将<canvas> 缩放到周围<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>

对于您的用例,您可以像这样更改代码:

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);}

【讨论】:

  • 谢谢!我会尝试使用它并告诉你它是否有效:)
  • 成功了!谢谢!我的代码中的另一个问题是,我也在使用 Vuetify.js,因此它会导致其他问题。
  • @RaulS 很高兴它有帮助:)
猜你喜欢
  • 2018-08-07
  • 2019-08-31
  • 2018-02-25
  • 2020-03-28
  • 2016-12-04
  • 2021-06-22
  • 2022-10-08
  • 2013-03-28
  • 1970-01-01
相关资源
最近更新 更多