Uncaught TypeError: Cannot read property 'position' of undefined in three.js in typescript
我在three.js中初始化摄像头位置有一个小问题。我用typescript写这个项目。浏览器控制台返回我:Uncaught TypeError:无法读取undefined的属性" position"。这是我在app.ts文件中的源代码:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 | ///<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); } } |
您知道如何解决此错误吗?
此错误的主要原因是您没有可用的PerspectiveCamera JavaScript ...
如果您下载Three.JS zip文件并包含
最好的选择是使用缩小的three.js文件,您将在这里找到:
http://threejs.org/build/three.min.js
这会将您需要的所有单个组件捆绑在一个缩小的脚本中,包括您的PerspectiveCamera。