截至 angular-cli 1.0.0:
npm install three --save
npm install @types/three --save-dev
- 在 AppComponent.html 中添加一个 div 元素:
<div #rendererContainer></div>
- 在AppComponent.ts中导入三个.js:
import * as THREE from 'three';
- 使用
@ViewChild('rendererContainer') rendererContainer: ElementRef; 获取 div 元素的句柄
- 在您的构造函数/生命周期方法中进行必要的设置。注意:
ViewChild 在ngAfterViewInit 之前不可用。
完整的应用组件:
import {Component, ViewChild, ElementRef} from '@angular/core';
import * as THREE from 'three';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
@ViewChild('rendererContainer') rendererContainer: ElementRef;
renderer = new THREE.WebGLRenderer();
scene = null;
camera = null;
mesh = null;
constructor() {
this.scene = new THREE.Scene();
this.camera = new THREE.PerspectiveCamera(75, window.innerWidth / window.innerHeight, 1, 10000);
this.camera.position.z = 1000;
const geometry = new THREE.BoxGeometry(200, 200, 200);
const material = new THREE.MeshBasicMaterial({color: 0xff0000, wireframe: true});
this.mesh = new THREE.Mesh(geometry, material);
this.scene.add(this.mesh);
}
ngAfterViewInit() {
this.renderer.setSize(window.innerWidth, window.innerHeight);
this.rendererContainer.nativeElement.appendChild(this.renderer.domElement);
this.animate();
}
animate() {
window.requestAnimationFrame(() => this.animate());
this.mesh.rotation.x += 0.01;
this.mesh.rotation.y += 0.02;
this.renderer.render(this.scene, this.camera);
}
}
完整的 AppComponent.html:
<div #rendererContainer></div>
如果你想使用一些额外的脚本:
您最终可能想要使用一些额外的脚本,例如加载器和控件。其中大部分没有被编写为模块,而是在加载时向window 上的THREE 命名空间添加功能。因此,我最终告诉 angular-cli 通过将以下内容添加到我的 .angular-cli.json 文件中手动加载我的脚本:
{
"apps": [
{
"scripts": [
"../node_modules/tween.js/src/Tween.js",
"../node_modules/three/build/three.js",
"../node_modules/stats.js/build/stats.min.js",
"../vendor/VRMLLoader.js",
"../vendor/OrbitControls.js"
],
...
请注意,您还需要处理您的 three.js @types 文件没有为这些附加脚本定义任何类型的事实。理想情况下,我想扩展现有的类型定义,但目前我只是通过在使用three.js 的文件顶部添加declare const THREE: any 来避免错误的提示,以解决three.js 的错误。如果您找到了一个很好的方法来扩展 @types/three 中的现有定义,请反馈!
调整窗口大小:
虽然我正在这样做,但我还会提到调整window 的大小可能会导致raycasting(我用来决定是否单击对象)之类的东西不再正常工作。要解决这个问题,只需:
@HostListener('window:resize', ['$event'])
onWindowResize(event) {
this.renderer.setSize(event.target.innerWidth, event.target.innerHeight)
}