Akhil Biju
Akhil Biju

Reputation: 33

three.js not working with angular 5

I recently got a project and i am using three.js for the graphics part in angular. Am new to both angular and three.js. The problem i am not able to setup the three.js with angular. Below are my setup

app.component.ts

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;
  title = 'app';
  camera; 
  renderer;
  geometry;
  material;
  mesh;
  cube;
  scene;

  constructor() {
    this.scene = new THREE.Scene();

    // Create a basic perspective camera
    this.camera = new THREE.PerspectiveCamera( 75, window.innerWidth/window.innerHeight, 0.1, 1000 );
    this.camera.position.z = 4;

    // Create a renderer with Antialiasing
    this.renderer = new THREE.WebGLRenderer({antialias:true});

    // Configure renderer clear color
    this.renderer.setClearColor("#000000");

    // Configure renderer size
    this.renderer.setSize( window.innerWidth, window.innerHeight );

    // Append Renderer to DOM
    document.body.appendChild( this.renderer.domElement );

    // ------------------------------------------------
    // FUN STARTS HERE
    // ------------------------------------------------

    // Create a Cube Mesh with basic material
    this.geometry = new THREE.BoxGeometry( 1, 1, 1 );
    this.material = new THREE.MeshBasicMaterial( { color: "#433F81" } );
    this.cube = new THREE.Mesh( this.geometry, this.material );

    // Add cube to Scene
    this.scene.add( this.cube );

  }  
  render();
  render () {
  requestAnimationFrame( this.render );

    this.cube.rotation.x += 0.01;
    this.cube.rotation.y += 0.01;

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

And this my HTML template of that component app.component.html

<div #rendererContainer></div>

The output is, just a big black screen. Am referring to this article to create a basic cube https://medium.com/@necsoft/three-js-101-hello-world-part-1-443207b1ebe1

Can anyone say what i am doing wrong ?

Upvotes: 0

Views: 2230

Answers (1)

theykillimmortal
theykillimmortal

Reputation: 149

I suppose the problem is in this line render(); You didn't call render function; because this call isn't in the constructor or another function. Please, call render() in ngOnInit() or in another function.

P.S. Maybe those examples will be useful for you. https://github.com/makimenko/angular-three-examples

Upvotes: 2

Related Questions