【发布时间】:2020-09-30 16:30:35
【问题描述】:
我目前正在尝试学习 Three.js,我正在一个 Vue.js 组件中进行学习, 这是我的代码:
<script>
import * as THREE from "three";
export default {
name: "Scene",
mounted() {
this.initThree();
},
methods: {
initThree() {
this.canvas = document.getElementById("background");
this.scene = new THREE.Scene();
this.camera = new THREE.PerspectiveCamera(75, 2, 0.1, 1000);
this.renderer = new THREE.WebGLRenderer({
canvas: this.canvas,
alpha: true,
antialias: true,
});
this.renderer.setSize(this.canvas.clientWidth, this.canvas.clientHeight);
let geometry = new THREE.BoxGeometry(1, 1, 1);
this.light = new THREE.DirectionalLight(0xffffff, 1);
this.light.position.set(4, -2, 2);
this.scene.add(this.light);
this.camera.position.z = 2;
this.cubes = [
this.makeInstance(geometry, 0x44aa88, 0),
this.makeInstance(geometry, 0x8844aa, -2),
this.makeInstance(geometry, 0xaa8844, 2),
];
this.animate();
},
animate() {
this.cubes.forEach((cube) => {
cube.rotation.y += 0.01;
});
this.resizeCanvasToDisplaySize();
this.renderer.render(this.scene, this.camera);
requestAnimationFrame(this.animate);
},
resizeCanvasToDisplaySize() {
const canvas = this.renderer.domElement;
// look up the size the canvas is being displayed
const width = canvas.clientWidth;
const height = canvas.clientHeight;
if (canvas.width !== width || canvas.height !== height) {
this.renderer.setSize(width, height, false);
this.camera.aspect = width / height;
this.camera.updateProjectionMatrix();
}
},
makeInstance(geometry, color, x) {
const material = new THREE.MeshPhongMaterial({ color });
const cube = new THREE.Mesh(geometry, material);
this.scene.add(cube);
cube.position.x = x;
return cube;
},
},
};
</script>
<style scoped>
canvas {
display: block;
width: 100%;
}
</style>
如果我将窗口大小调整为小于初始大小(加载页面时的大小),在 chrome 上的开发人员工具中,它可以正常工作,画布宽度和高度会正确更改。如果我使尺寸大于初始尺寸,它会保持不变并且根本不会缩放。此外,缩放仅适用于开发工具而不是实际窗口。
【问题讨论】:
-
我建议你换个方式,注册一个事件监听器到
resize事件。然后,您可以使用与此基本示例相同的实现:threejs.org/examples/webgl_geometry_cube
标签: javascript vue.js three.js