Using threejs with angular

I used Angular 7 with three.js to make a 3D viewer. The goal was to write a generic Angular component loading three.js that can easily be used by any project and then apply the application logic afterwards.

The project's source code can be found here: github.com/saaratrix/generic-3Dproduct-viewer
The generic Angular component can be found here: github.com/saaratrix/generic-3Dproduct-viewer/tree/master/src/app/viewer-threejs
The application can be demoed here: saaratrix.github.io/generic-3Dproduct-viewer/build/

How it works

The app component's HTML code:


<div class="container-3D">
  <app-viewer-threejs (sceneInit)="onSceneInit($event)" ></app-viewer-threejs>
  <app-toolbar></app-toolbar>
  <app-loading-spinner *ngIf="loadingsStarted !== loadingsFinished"></app-loading-spinner>
</div>

            

<app-viewer-threejs> is the generic Angular component. The component has an input event called sceneInit which dispatches when the WebGLRenderer has been created. In the app component's onSceneInit() the class ProductConfigurator is created which does all the 3D logic. Such as set up the camera, the scene with lights etc.

The app is structured so there are 2 different parts, Angular components for the view and 3D logic for the 3D. I wanted the three.js component to only set up the WebGLRenderer so there's no logic in that component itself.

Sharing data

The service ProductConfiguratorService is used to share data between classes and components. In the service I use Subject to handle events that can happen in the application.
For example a user clicks a button to change a 3D model. The action dispatches an event ChangeProduct which all subscriptions can handle how they seem fit.

Afterwords

This is one way of using Angular and three.js. This worked well for my goals and it's a small application so I can't say if it scales to a massive code base. But for now it's easy to create new events and handle them.

No comments:

Post a Comment