Three.js Cube

I’ve been working with Three.js to create scenes and fun games. One of the things I wanted to do was put together a brief tutorial as I am learning. Document for posterity. So, in 3D World a Hello World would be rendering a primitive within a scene. In Three.JS there are three components required to actually see anything

  • Scene
  • Camera
  • Renderer

The scene is the universe that everything lives within. Camera is the view into that universe. Renderer is the engine used to draw pixels. So at a minimum we need

1
2
3
const scene = new THREE.Scene();
const camera = new THREE.PerspectiveCamera(75, window.innerWidth/ window.innerHeight, 0.1, 1000);
const renderer = new THREE.WebGLRenderer();

The dom element of our Renderer gets added to the doc body and from that you are ready to create something within a Three.JS app. In this case I will create a cube primitive and just rotate it.

1
2
3
const geometry = new THREE.BoxGeometry(1, 1, 1); 
const material = new THREE.MeshBasicMaterial({ color: 0x00ff00 });
const cube = new THREE.Mesh(geometry, material);

This is added to the scene and then I adjst the z scale slightly to allow for a slightly better angle. From that the animation is is rotating about the cube’s x & y. I’ve added my implementation of this below:

Play Now