Vue and Threejs - Part One

March 19th, 2019

Let's set up a Vue application with a three dimensional user experience powered by Three.js.

The completed code for this project is available here. You can also check out a demo. Our goal will be to convert this Three.js Example into a Vue application, and perhaps add a bit more functionality while we are at it.

To start, spin up a new vue application with the Vue CLI tool. (If you haven't done that before, check out this great tutorial.) For the sake of this tutorial you can choose any of the settings that you are comfortable with; just make sure you choose to have Vuex added to the project.

Next, we will add Three.js to the project with NPM. You can install it directly via NPM, however it does not yet play nicely with ES6 imports. To get around this, we can use the three-full mirror, which delivers Three.js in a format that is much easier to use with ES6 style imports. Let's install that now:

$ npm install three-full

We can now get our development server up and running by using:

$ npm run serve

The first thing we will do is remove the HelloWorld.vue file that came with your new application and we will also remove all references to that file from App.vue. We can also remove the default styles from the bottom of the App.vue file and replace them with this:

<style>
html,
body {
  width: 100%;
  height: 100%;
  overflow: hidden;
}
body {
  margin: 0px;
}

#app {
  height: 100%;
}
</style>

Here we are removing the default padding from the html and body tags and making sure that our #app div will fill the entire visible browser window.

We will use a ViewPort component to manage the canvas element generated by Three.js; let's create that now. Add a new file called ViewPort.vue in your /src/components directory. We can now import that into the main App.vue component. Update the script section in that file to look like this:

import ViewPort from "@/components/ViewPort.vue";

export default {
  components: {
    viewport: ViewPort,
  }
};

And we can now use that component in our App.vue template:

<template>
  <div id="app">
    <viewport/>
  </div>
</template>

Let's now turn our attention to getting Three.js up and running. Three.js renders three dimensional scenes on canvas elements; before you can render a scene you need to create Camera, Control and Scene objects, that you will then give to a WebGLRender to have the canvas element generated for you. Three.js provides tools for creating all of these objects and populating the scene with three dimensional objects.

We are going to let Vuex manage the various components of our Three.js scene; this will make it much easier for us to modify the scene contents once they have been created, as we will explore in part two. Open your store.js file, and update the top of the file to look like this:

import Vue from "vue";
import Vuex from "vuex";
import {
  Scene,
  TrackballControls,
  PerspectiveCamera,
  WebGLRenderer,
  Color,
  FogExp2,
  CylinderBufferGeometry,
  MeshPhongMaterial,
  Mesh,
  DirectionalLight,
  AmbientLight,
  LineBasicMaterial,
  Geometry,
  Vector3,
  Line
} from "three-full";

Vue.use(Vuex);

Here we are importing Vue, Vuex and a litany of Three.js objects that we will use to create our scene. We are going to use vuex mutations to manage the creation of the scenes, and a vuex action to trigger those mutations. The general rule of thumb is that actions are used to handle asynchronous updates, and mutations must always be used for synchronous updates. In a normal Vuex workflow, you might have an action that makes an http request, which would then hand off the response data to mutations to store that data in the vuex state, which is where everything is kept.

Let's start by adding some new items to our state object:

state: {
  width: 0,
  height: 0,
  camera: null,
  controls: null,
  scene: null,
  renderer: null,
  axisLines: [],
  pyramids: []
},

We will use width and height to keep track of the canvas size. camera, controls, scene and renderer will be use to store the tools generated by Three.js. axisLines and pyramids will be used to keep track of the visual elements used in our scene; the scenery if you will.

First up, lets create a mutation that sets the height and width of the canvas. By convention, all vuex method names are upper case:

mutations: {
  SET_VIEWPORT_SIZE(state, { width, height }) {
    state.width = width;
    state.height = height;
  },
}

Here we are receiving a width and a height and updating the state accordingly. Next, lets create our renderer:

mutations: {
  // ...
  INITIALIZE_RENDERER(state, el) {
    state.renderer = new WebGLRenderer({ antialias: true });
    state.renderer.setPixelRatio(window.devicePixelRatio);
    state.renderer.setSize(state.width, state.height);
    el.appendChild(state.renderer.domElement);
  },
}

Here we are instantiating a new WebGLRenderer (provided by Three.js) and setting the width and height of the scene that we want to create. Note that we this function receives a reference to a dom element (often referred to as el). The WebGLRenderer will create a canvas element for us, but it won't be visible unless we actually add it to the dom tree. el.appendChild adds the canvas element as a child node the el dom element.

Now lets create our camera:

mutations: {
  // ...
  INITIALIZE_CAMERA(state) {
    state.camera = new PerspectiveCamera(
      // 1. Field of View (degrees)
      60,
      // 2. Aspect ratio
      state.width / state.height,
      // 3. Near clipping plane
      1,
      // 4. Far clipping plane
      1000
    );
    state.camera.position.z = 500;
  },
}

Here we are creating a new PerspectiveCamera object with four parameters: The field of view of the camera's "lens" in degrees, the aspect ratio of the camera's output, and the "clipping plane" boundaries. Anything further than 1000 units away from the camera will not be visible. Finally, we set the starting position of the camera at 500 units away from origin on the z-axis.

Now lets create our controls:

mutations: {
  // ...
  INITIALIZE_CONTROLS(state) {
    state.controls = new TrackballControls(
      state.camera,
      state.renderer.domElement
    );
    state.controls.rotateSpeed = 1.0;
    state.controls.zoomSpeed = 1.2;
    state.controls.panSpeed = 0.8;
    state.controls.noZoom = false;
    state.controls.noPan = false;
    state.controls.staticMoving = true;
    state.controls.dynamicDampingFactor = 0.3;
  },
}

Here we instantiate a new TrackballControls object and set up a default configuration for it. The exact nature of this configuration is a bit beyond the scope of this tutorial, but you should feel free to play around with these values and see what happens.

The most important thing to note here is that we are passing in our canvas element as the second argument to the TrackballControls constructor. This will limit the controls to listen only for input events that occur on that dom element. If you don't provide this, it will default to listening to all input events on the entire document which will effectively steal focus away from any other content on the page and translate all input into camera movements in the rendered scene. By limiting this to just the canvas element we will still be able to interact with other content on the page normally.

Next up, the scene content itself. This one is a doozy:

mutations: {
  // ...
  INITIALIZE_SCENE(state) {
    state.scene = new Scene();
    state.scene.background = new Color(0xcccccc);
    state.scene.fog = new FogExp2(0xcccccc, 0.002);
    var geometry = new CylinderBufferGeometry(0, 10, 30, 4, 1);
    var material = new MeshPhongMaterial({
      color: 0xffffff,
      flatShading: true
    });
    for (var i = 0; i < 500; i++) {
      var mesh = new Mesh(geometry, material);
      mesh.position.x = (Math.random() - 0.5) * 1000;
      mesh.position.y = (Math.random() - 0.5) * 1000;
      mesh.position.z = (Math.random() - 0.5) * 1000;
      mesh.updateMatrix();
      mesh.matrixAutoUpdate = false;
      state.pyramids.push(mesh);
    }
    state.scene.add(...state.pyramids);

    // lights
    var lightA = new DirectionalLight(0xffffff);
    lightA.position.set(1, 1, 1);
    state.scene.add(lightA);
    var lightB = new DirectionalLight(0x002288);
    lightB.position.set(-1, -1, -1);
    state.scene.add(lightB);
    var lightC = new AmbientLight(0x222222);
    state.scene.add(lightC);

    // Axis Line 1
    var materialB = new LineBasicMaterial({ color: 0x0000ff });
    var geometryB = new Geometry();
    geometryB.vertices.push(new Vector3(0, 0, 0));
    geometryB.vertices.push(new Vector3(0, 1000, 0));
    var lineA = new Line(geometryB, materialB);
    state.axisLines.push(lineA);

    // Axis Line 2
    var materialC = new LineBasicMaterial({ color: 0x00ff00 });
    var geometryC = new Geometry();
    geometryC.vertices.push(new Vector3(0, 0, 0));
    geometryC.vertices.push(new Vector3(1000, 0, 0));
    var lineB = new Line(geometryC, materialC);
    state.axisLines.push(lineB);

    // Axis 3
    var materialD = new LineBasicMaterial({ color: 0xff0000 });
    var geometryD = new Geometry();
    geometryD.vertices.push(new Vector3(0, 0, 0));
    geometryD.vertices.push(new Vector3(0, 0, 1000));
    var lineC = new Line(geometryD, materialD);
    state.axisLines.push(lineC);

    state.scene.add(...state.axisLines);
  },
}

Most of this comes directly from the Three.js example that we are emulating, however there are couple important differences to note:

Next we will create a mutation that will handle resizing the canvas element for us:

mutations: {
  // ...
  RESIZE(state, { width, height }) {
    state.width = width;
    state.height = height;
    state.camera.aspect = width / height;
    state.camera.updateProjectionMatrix();
    state.renderer.setSize(width, height);
    state.controls.handleResize();
    state.renderer.render(state.scene, state.camera);
  },
}

This should be pretty straight forward. When we want to resize the canvas we call this mutation and provide it with our new width and height. It then updates the camera and renderer accordingly and re-renders the scene using the new dimensions.

Finally, we will now set up two vuex actions that will orchestrate these various mutations for us. First we will use an action to initialize our scene on page load:

actions: {
  INIT({ state, commit }, { width, height, el }) {
    return new Promise(resolve => {
      commit("SET_VIEWPORT_SIZE", { width, height });
      commit("INITIALIZE_RENDERER", el);
      commit("INITIALIZE_CAMERA");
      commit("INITIALIZE_CONTROLS");
      commit("INITIALIZE_SCENE");

      // Initial scene rendering
      state.renderer.render(state.scene, state.camera);

      // Add an event listener that will re-render
      // the scene when the controls are changed
      state.controls.addEventListener("change", () => {
        state.renderer.render(state.scene, state.camera);
      });

      resolve();
    });
  },
}

The init function returns a promise that resolves once all of our various Three.js components have been created and registered. It also takes care of the initial scene rendering and sets an event listener that will re-render the scene if the controls receive an input trigger.

Finally, we will use an action to set up our animation loop. This is a recursive function that re-renders the scene (if needed) during every tick of the event loop. We could use setTimeout here, but requestAnimationFrame does the same thing except that it will pause the animation loop if the browser looses focus. See more about animation frames here.

actions: {
  // ..
  ANIMATE({ state, dispatch }) {
    window.requestAnimationFrame(() => {
      dispatch("ANIMATE");
      state.controls.update();
    });
  }
}

That should cover everything we need to get our 3D scene up and running. Now lets put it all together in our ViewPort component. The template and the styling of this component are very straight forward:

<template>
  <div class="viewport"/>
</template>

We create a single dom node (the root node for this component) which will become a wrapper around the canvas element generated by our WebGLRenderer.

<style>
  .viewport {
    height: 100%;
    width: 100%;
  }
</style>

Here we are setting the height and width of the component to be 100% of its parent node, which in this case happens to be the main #app div (the root node of the App.vue component.) This will ensure that our canvas element uses the entire browser screen.

The real fun is in the script section of the component:

import { mapMutations, mapActions } from "vuex";

export default {
  data () {
    return {
      height: 0
    };
  },
  methods: {
    ...mapMutations(["RESIZE"]),
    ...mapActions(["INIT", "ANIMATE"])
  },
  mounted () {
    this.INIT({
      width: this.$el.offsetWidth,
      height: this.$el.offsetHeight,
      el: this.$el
    }).then(() => {
      this.ANIMATE();
      window.addEventListener("resize", () => {
        this.RESIZE({
          width: this.$el.offsetWidth,
          height: this.$el.offsetHeight
        });
      });
    });
  }
};

To start, we import some helper methods from Vuex which will allow us to reference our vuex actions and mutations directly from this component. Next, when the component is mounted (on page load) we will trigger our INIT function, creating our three dimensional scene. When it is ready we will trigger our animation loop and set an event listener that triggers our RESIZE function whenever the browser window is resized.

That should be everything we need! Take a look at the URL being used by your dev server (usually http://localhost:8080/) to see your beautifully rendered scene.

The next installment of this tutorial will investigate creating a control panel that will allow users to manually manipulate the rendered scene.

More in this series: