JohnnyDevNull / ng-three-template

This is a basic template project to start with Angular 17.x and ThreeJS
MIT License
228 stars 71 forks source link

First loading in browser don't work #3

Closed zoujagger closed 5 years ago

zoujagger commented 5 years ago

Hi, thanks for your good job. I created spher with your methid using service and component. When i launch my application in the browser the first time my component don't renderer. But it's work when i refresh.ha ve you an idea to solve this. thanks my compoent :

import {Component, ViewChild, ElementRef, OnDestroy, AfterViewInit} from '@angular/core'; import * as THREE from 'three'; import { SphereService } from './sphere.service';

@Component({ selector: 'app-sphere', templateUrl: './sphere.component.html', styleUrls: ['./sphere.component.sass'] }) export class SphereComponent implements AfterViewInit, OnDestroy {

@ViewChild('rendererCanvas') public rendererCanvas: ElementRef;

constructor(private sphereService: SphereService) {}

ngAfterViewInit() { this.sphereService.running = true; this.sphereService.createScene(this.rendererCanvas); this.sphereService.animate();

}

ngOnDestroy(): void { this.sphereService.running = false; } }

my service

import { Injectable, ElementRef, OnDestroy, NgZone } from '@angular/core'; import * as THREE from 'three'; import { SphereModel } from './sphere.model';

@Injectable({ providedIn: 'root' }) export class SphereService implements OnDestroy {

private canvas: HTMLCanvasElement; private renderer: THREE.WebGLRenderer; private camera: THREE.PerspectiveCamera; private scene: THREE.Scene; private frameId: number = null; private arrayOfThreeSpheres: SphereModel[] = new Array(); private sphere;

// controle running public running: boolean;

public constructor(private ngZone: NgZone) {}

public ngOnDestroy() { if (this.frameId != null) { cancelAnimationFrame(this.frameId); } }

createScene(canvas: ElementRef): void {

// Check that we're still running.
if (!this.running) {
  return;
}

// The first step is to get the reference of the canvas element from our HTML document
this.canvas = canvas.nativeElement;
console.log('canvas reference---->', this.canvas);

this.renderer = new THREE.WebGLRenderer({
  canvas: this.canvas,
  alpha: false,    // transparent background
  antialias: true // smooth edges
});
// renderer = new THREE.CanvasRenderer();

this.renderer.setSize(window.innerWidth, window.innerHeight);

// create the scene
this.scene = new THREE.Scene();

this.camera = new THREE.PerspectiveCamera(45, 1.0);
this.camera.position.set(0, 0, +1000);

for (let i = 1; i <= 3; i++) {
  const p = ( (v) => {let r = 0; (v >= 0.5) ? r = 1 : r = -1; return r; })(Math.random());
  const q = ( (v) => {let r = 0; (v >= 0.5) ? r = 1 : r = -1; return r; })(Math.random());
  const r = ( (v) => {let r = 0; (v >= 0.5) ? r = 1 : r = -1; return r; })(Math.random());
  console.log('r -->' + r + 'q -->' + q + 'p -->' + p);
  if(i === 1) {
    this.sphere = new SphereModel(i * 100, 30, 30, 0.03 * p, 0.03 * q , 0.03 * r, '#7B68EE');
  }
  if(i === 2) {
    this.sphere = new SphereModel(i * 100, 30, 30, 0.03 * p, 0.03 * q , 0.03 * r, '#2E8B57');
  }
  if(i === 3) {
    this.sphere = new SphereModel(i * 100, 30, 30, 0.03 * p, 0.03 * q , 0.03 * r, '#DC143C');
  }
  console.log('on build sphere');
  this.scene.add(this.sphere.getMesh());
  this.arrayOfThreeSpheres.push(this.sphere);
}

// tick();
// function tick() {
//   for (let i = 0; i < array.length; i++) {
//     array[i].next();
//     console.log('array[i]----->', array[i]);
//   }

//   this.render();
// }
// this.animate();

}

tick() { // tslint:disable-next-line:prefer-for-of for (let i = 0; i < this.arrayOfThreeSpheres.length; i++) { this.arrayOfThreeSpheres[i].next(); console.log('array[i]----->', this.arrayOfThreeSpheres[i]); }

}

animate(): void { // We have to run this outside angular zones, // because it could trigger heavy changeDetection cycles. this.ngZone.runOutsideAngular(() => { window.addEventListener('DOMContentLoaded', () => { this.render(); });

  window.addEventListener('resize', () => {
    this.resize();
  });
});

}

render(): void { this.frameId = requestAnimationFrame(() => { this.render(); });

this.tick();
this.renderer.render(this.scene, this.camera);

}

resize() { const width = window.innerWidth; const height = window.innerHeight;

this.renderer.setPixelRatio(window.devicePixelRatio);
this.renderer.setSize(width, height);
this.camera.aspect = width / height;
this.camera.updateProjectionMatrix();

} }

the model

import * as THREE from 'three';

export class SphereModel { private geometry; private material; private materialParam; private mesh;

constructor(private radius, private widthseg, private heightseg, private rotx, private roty, private rotz, private colorSphere) {

this.geometry = new THREE.SphereGeometry(this.radius, this.widthseg, this.heightseg);
this.materialParam = {
        color: this.colorSphere,
        wireframe: true ,
        blending: THREE.AdditiveBlending,
        transparent: true
    };
this.material = new THREE.MeshBasicMaterial(this.materialParam);
this.mesh = new THREE.Mesh(this.geometry, this.material);
this.rotx = rotx / 20;
this.roty = roty / 15;
this.rotz = rotz / 20;

}

getColor() { return '#' + Math.floor(Math.random() * 16777215).toString(16); }

getMesh() { return this.mesh; }

next() { this.mesh.rotation.x += this.rotx; this.mesh.rotation.y += this.roty; this.mesh.rotation.z += this.rotz; }

}

JohnnyDevNull commented 5 years ago

Hi there,

is your problem still active or did you get rid of?

greetings

JohnnyDevNull commented 5 years ago

Closed because of no reaction...