Three.js

From ImpVis Wiki
Revision as of 01:03, 26 July 2022 by SarmpaviUthayakumar (talk | contribs) (Added summer 2022 category)
Jump to navigation Jump to search

Introduction

Author - Sarmpavi

This page provides some basic information on how to use Three.js including example code and some useful resources to learn and gain more knowledge about the package. Please note that the example code has been written by myself with only a few weeks of Three.js experience – a lot of improvements can be made but I hope this will be somewhat useful for any beginners who are reading this. This page also assumes that you have some basic JavaScript/HTML/CSS knowledge.

Three.js is a library which allows you to create 3D content and is a useful tool when developing interactive visualisations.

Installation:

Three.js can be installed by navigating to your project folder in your terminal and then typing: npm install three

Once installed, import it into your JavaScript file: import * as THREE from "../node_modules/three/build/three.module.js"; (insert image)

Orbit controls:

The Orbit controls package must also be imported – this allows you to interact with (e.g. rotate, pan, zoom in/out) your 3D object. To import this into your JavaScript file - import {OrbitControls} from "../vendor_mods/three/examples/jsm/controls/OrbitControls.js"; (pic)

Scene

First, we construct the ‘Scene’ which can be thought of as the canvas for the 3D object. To create the Scene – const scene = new THREE.Scene()

Camera

The camera controls how the user views the 3D object on the scene. There are lots of different types of cameras but generally the ‘PerspectiveCamera’ is used where objects further away appear smaller just how the human eye sees things.

const camera = new THREE.PerspectiveCamera()

PerspectiveCamera takes several variables in which one can define the type of lens (wide-angle, telephoto) and the aspect ratio. If we want the scene to cover the entire page, the aspect ratio is window.innerWidth/window.innerHeight.

The position of the camera can be changed by setting the x, y and z positions:

camera.position.x = (enter float)

camera.position.y = (enter float)

camera.position.z = (enter float)

We must finally add the camera to the Scene: scene.add(camera)

Mesh

To add the 3D object, we use ‘Mesh’. The Mesh is made up of two variables: the geometry (the shape of the object) and the material (how the geometry looks). Let us take the example of a sphere.



Finally add the object to the Scene:




Link to example code:


Screenshot of Three.js visualisation:


Things to work on in future:

-         Integration with the ImpVis template: Found it difficult to use import Three.js into the template