动态背景插件three.min.ts

引入three.min.ts

1、ts文件

import { Component, OnInit, ViewChild, ElementRef, AfterViewInit } from '@angular/core';

@Component({
selector: 'app-comp',
templateUrl: './comp.component.html',
styleUrls: ['./comp.component.less']
})
export class CompComponent implements OnInit , AfterViewInit{
@ViewChild('cloud') cloud: ElementRef;
SEPARATION = 100;
AMOUNTX = 50;
AMOUNTY = 50;
container;
camera;
scene;
renderer;
particles;
particle; count = 0;
mouseX = 618;
mouseY = -312;
windowHalfX;
windowHalfY;

constructor() { }

ngAfterViewInit() {
this.windowHalfX = window.innerWidth / 2;
this.windowHalfY = window.innerHeight / 2;
this.container = document.createElement( 'div' );
this.container.setAttribute("class", "canvas");
this.cloud.nativeElement.appendChild( this.container );
this.camera = new THREE.PerspectiveCamera( 75, window.innerWidth / window.innerHeight, 1, 10000 );
this.camera.position.z = 1000;
this.scene = new THREE.Scene();
this.particles = new Array();
const PI2 = Math.PI * 2;
const material = new THREE.ParticleCanvasMaterial( {
color: 0x017dd7,
program: function ( context ) {
context.beginPath();
context.arc( 0, 0, 1, 0, PI2, true );
context.fill();
}

} );

let i = 0;
for ( let ix = 0; ix < this.AMOUNTX; ix ++ ) {
for ( let iy = 0; iy < this.AMOUNTY; iy ++ ) {
this.particle = this.particles[ i ++ ] = new THREE.Particle( material );
this.particle.position.x = ix * this.SEPARATION - ( ( this.AMOUNTX * this.SEPARATION ) / 2 );
this.particle.position.z = iy * this.SEPARATION - ( ( this.AMOUNTY * this.SEPARATION ) / 2 );
this.scene.add( this.particle );
}

}
const that = this;
this.renderer = new THREE.CanvasRenderer();
this.renderer.setSize( window.innerWidth, window.innerHeight/2 );
this.container.appendChild( this.renderer.domElement );
window.addEventListener( 'resize', that.onWindowResize, false );
const animate = function() {
requestAnimationFrame(animate);
that.render();
}
animate();
}

onWindowResize() {
this.windowHalfX = window.innerWidth / 2;
this.windowHalfY = window.innerHeight / 2;
}

render() {
this.camera.position.x += ( this.mouseX - this.camera.position.x ) * .05;
this.camera.position.y += ( - this.mouseY - this.camera.position.y ) * .05;
this.camera.lookAt( this.scene.position );
let i = 0;
for ( let ix = 0; ix < this.AMOUNTX; ix ++ ) {
for ( let iy = 0; iy < this.AMOUNTY; iy ++ ) {
this.particle = this.particles[ i++ ];
this.particle.position.y = ( Math.sin( ( ix + this.count ) * 0.3 ) * 50 ) + ( Math.sin( ( iy + this.count ) * 0.5 ) * 50 );
this.particle.scale.x = this.particle.scale.y = ( Math.sin( ( ix + this.count ) * 0.3 ) + 1 ) * 2 + ( Math.sin( ( iy + this.count ) * 0.5 ) + 1 ) * 2;
}
}
this.renderer.render( this.scene, this.camera );
this.count += 0.1;
}

ngOnInit() {
}

}

2、html文件

<div #cloud></div>
原文地址:https://www.cnblogs.com/boreguo/p/10595277.html