我需要使渲染器的大小适合网页上元素的大小。进行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);}
预期:如果您取消注释注释,则整个渲染器将占据整个窗口的大小。
实际:我必须自己对尺寸进行硬编码,但这只是一个修补程序:(
答案 0 :(得分:0)
您可以使用<canvas>
获取包含渲染器(getBoundingClientRect
)的元素的尺寸。以下是一个小示例,展示了<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);}