Like angular-cli 1.0.0:
npm install three --savenpm install @types/three- Add div element in AppComponent.html:
<div #rendererContainer></div> - Import the three.js file into AppComponent.ts:
import * as THREE from 'three'; - Get the handle of a div element using
@ViewChild('rendererContainer') rendererContainer: ElementRef; - Make the necessary adjustments in your constructors / life cycles. Note:
ViewChildnot available until ngAfterViewInit.
Full AppComponent:
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);
}
}
Full AppComponent.html:
<div #rendererContainer></div>
:
, , . , THREE window . - 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 - . , hinting 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)
}