import { Component, OnInit, ElementRef } from '@angular/core'; import * as THREE from 'three'; @Component({ selector: '[mat-crystal-structure]', template: ``, styleUrls: ['./mat-crystal-structure.component.less'] }) export class MatCrystalStructureComponent implements OnInit { renderer: any; camera: any; scene: any; light: any; cube: any; mesh: any; width: any; height: any; constructor(private _el: ElementRef) {} initThree() { this.width = this._el.nativeElement.clientWidth; this.height = this._el.nativeElement.clientHeight; this.renderer = new THREE.WebGLRenderer({ antialias: true }); this.renderer.setSize(this.width, this.height); this._el.nativeElement.appendChild(this.renderer.domElement); this.renderer.setClearColor(0xFFFFFF, 1); } initCamera() { this.camera = new THREE.PerspectiveCamera(45, this.width / this.height, 1, 10000); this.camera.position.x = 100; this.camera.position.y = 300; this.camera.position.z = 600; this.camera.up.x = 0; this.camera.up.y = 1; this.camera.up.z = 0; /** * 注意lookAt的参数 * https://github.com/mrdoob/three.js/blob/master/src/core/Object3D.js **/ this.camera.lookAt(0, 0, 0); } initScene() { this.scene = new THREE.Scene(); } initLight() { this.light = new THREE.DirectionalLight(0xFF0000, 1, 0); this.light.position.set(100, 100, 200); this.scene.add(this.light); } initObject() { const geometry = new THREE.BoxGeometry(150, 150, 150); for (let i = 0; i < geometry.faces.length; i += 2) { const hex = Math.random() * 0xFFFFFF; geometry.faces[i].color.setHex(hex); geometry.faces[i + 1].color.setHex(hex); } const material = new THREE.MeshBasicMaterial({ vertexColors: THREE.FaceColors }); this.mesh = new THREE.Mesh(geometry, material); // mesh.position = new THREE.Vector3(0, 0, 0); this.scene.add(this.mesh); } // 帧循环、游戏循环 animation() { this.mesh.rotateY(0.01); this.renderer.render(this.scene, this.camera); // https://stackoverflow.com/questions/43466240/requestanimationframe-is-being-called-only-once requestAnimationFrame(this.animation.bind(this)); } threeStart() { this.initThree(); this.initCamera(); this.initScene(); this.initLight(); this.initObject(); this.animation(); } ngOnInit() { // this.threeStart(); } }