3JS #00 – Starting to learn three.js again

Let’s try if the script works with squarespace’s code block. The code block didn’t work. But the embed seems to work fine. I wanted to see the coded part as well, but seems only the final rendering is working with codesandbox.io so back to the drawing board. Added the source code to the left, so it is good enough for now. Alright. The text won’t probably show the time passed between sentences, but this is more of a documentation, so I’ll leave these notes at that.

I want to recap though: to create a rendering of 3d objects in web using three.js we need 4 things:

  1. The Scene: We simply add a new THREE.Scene();

  2. The Object: We choose the Geometry, the Material then combine the two into a Mesh, and we add the Mesh to the Scene

  3. The Camera: We add a new camera to look at the scene and objects we created. Always remember to move the camera positively in the z-axis to pull away from the origin point and view from the front.

  4. The Renderer: Finally we need the renderer to actually see all these things including the Scene. Renderer is usually the browser window itself or we can think of it as creating a viewport into the 3d world. It is attached to the <canvas> element in the HTML.

Haven’t learned the animate frames part yet, but thought to add rotation let this embed render be more than a static red box.

import * as THREE from "three";

//scene
const scene = new THREE.Scene();

//geometry, material, and mesh
const geometry = new THREE.BoxGeometry(1, 1, 1);
const material = new THREE.MeshBasicMaterial({ color: 0xff0000 });
const mesh = new THREE.Mesh(geometry, material);
//add mesh to scene
scene.add(mesh);

//sizes
const sizes = {
  width: 800,
  height: 600
};

//camera
const camera = new THREE.PerspectiveCamera(75, sizes.width / sizes.height);
camera.position.z = 3;
scene.add(camera);

//renderer
// Canvas
const canvas = document.querySelector("canvas.webgl");

// Renderer
const renderer = new THREE.WebGLRenderer({
  canvas: canvas
});

renderer.setSize(sizes.width, sizes.height);
renderer.render(scene, camera);

const tick = () => {
  // Update objects
  mesh.rotation.y += 0.01;

  // Render
  renderer.render(scene, camera);

  // Call tick again on the next frame
  window.requestAnimationFrame(tick);
};

tick();
 
Previous
Previous

WTA #01 – Thinking about the Dashboard

Next
Next

WTA #00 – Watchtides Redesign KickOff