Skip to content

Instantly share code, notes, and snippets.

@steveblue
Last active February 24, 2018 00:50
Show Gist options
  • Select an option

  • Save steveblue/e08d4e6e672c62b692d8c1ca80501103 to your computer and use it in GitHub Desktop.

Select an option

Save steveblue/e08d4e6e672c62b692d8c1ca80501103 to your computer and use it in GitHub Desktop.
An Example of THREE.js Scene in Angular Directive
import { Directive, ElementRef, AfterViewInit } from '@angular/core';
import { WindowRef } from './../../injectables/window/window.service';
import { PerspectiveCamera, Scene, WebGLRenderer, BoxGeometry, MeshNormalMaterial, Mesh } from 'three';
@Directive({
selector: '[threeCanvas]'
})
export class ThreeCanvasDirective implements AfterViewInit {
camera: PerspectiveCamera;
scene: Scene;
renderer: WebGLRenderer;
geometry: BoxGeometry;
material: MeshNormalMaterial;
mesh: Mesh;
window: Window;
constructor(private _elem: ElementRef, private _window: WindowRef) {
this.window = this._window.nativeWindow;
}
ngAfterViewInit() {
this.init();
this.animate();
}
init() {
this.camera = new PerspectiveCamera(70, this.window.innerWidth / this.window.innerHeight, 0.01, 10);
this.camera.position.z = 1;
this.scene = new Scene();
this.geometry = new BoxGeometry(0.2, 0.2, 0.2);
this.material = new MeshNormalMaterial();
this.mesh = new Mesh(this.geometry, this.material);
this.scene.add(this.mesh);
this.renderer = new WebGLRenderer({ antialias: true, canvas: this._elem.nativeElement });
this.renderer.setSize(this.window.innerWidth, this.window.innerHeight);
}
animate() {
this.window.requestAnimationFrame( this.animate.bind(this) );
this.mesh.rotation.x += 0.01;
this.mesh.rotation.y += 0.02;
this.renderer.render( this.scene, this.camera );
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment