我在three.js初始化摄像机位置时遇到小问题。我用打字稿写这个项目。浏览器控制台返回我:Uncaught TypeError:无法读取未定义的属性“position”。这是app.ts文件中的源代码:
///<reference path="Lib/three.d.ts">
class Rendering {
camera: THREE.PerspectiveCamera;
scene: THREE.Scene;
renderer: THREE.CanvasRenderer;
windowHalfX: number;
windowHalfY: number;
constructor() {
this.windowHalfY = window.innerHeight/2;
this.windowHalfX = window.innerWidth / 2;
}
public init() {
var container = document.createElement('div');
document.body.appendChild(container);
this.camera = new THREE.PerspectiveCamera(60, this.windowHalfX / this.windowHalfY, 1, 1000);
this.camera.position.y = 100; // HERE CONSOLE CANNOT READ POSITION PROPERTY
this.camera.position.z = 200;
this.scene = new THREE.Scene();
this.renderer = new THREE.CanvasRenderer();
this.renderer.setSize(this.windowHalfX*2, this.windowHalfY*2);
container.appendChild(this.renderer.domElement);
var cubeGeometry = new THREE.CubeGeometry(150, 150, 150);
for (var i = 0; i < cubeGeometry.faces.length; i += 2) {
var hex = Math.random() * 0xffffff;
cubeGeometry.faces[i].color.setHex(hex);
cubeGeometry.faces[i + 1].color.setHex(hex);
}
var material = new THREE.MeshBasicMaterial({ vertexColors: THREE.FaceColors, overdraw: 0.5 });
var cube = new THREE.Mesh(cubeGeometry, material);
cube.position.y = 150;
this.scene.add(cube);
}
public render() {
this.camera.lookAt(this.scene.position);
this.renderer.render(this.scene, this.camera);
}
}
知道如何修复此错误吗?
答案 0 :(得分:3)
此错误的主要原因是您没有可用的PerspectiveCamera JavaScript ...
如果您下载了Three.JS zip文件并包含three.js
- 这不是您网页上所需的全部内容。
您最好的选择是使用您在此处找到的缩小的three.js文件:
http://threejs.org/build/three.min.js
这将在一个缩小的脚本中捆绑您需要的所有单个组件,包括您的PerspectiveCamera。