English 中文(简体)
Three.js - Hello Cube App
  • 时间:2024-11-03

Three.js - Hello Cube App


Previous Page Next Page  

Like any other programming language, let s start learning Three.js by creating "Hello cube!" app.

The HTML


<!DOCTYPE html>
<html>
   <head>
      <meta name="viewport" content="width=device-width, initial-scale=1" />
      <meta charset="UTF-8" />
      <title>Three.js - Hello cube</title>
      <style>
         /* Our CSS goes here */
      </style>
      <script src="https://cdnjs.cloudflare.com/ajax/pbs/three.js/r127/three.min.js"></script>
   </head>
   <body>
      <span id="threejs-container">
         <!-- Our output to be rendered here →
      </span>
      <script type="module">
         // our JavaScript code goes here
      </script>
   </body>
</html>

As you can see, it s just a simple HTML file with Three.js CDN.

The CSS


<style>
* {
   margin: 0;
   padding: 0;
   box-sizing: border-box;
   font-family: -apple-system, BpnkMacSystemFont, "Segoe UI", Roboto,
   Oxygen,
   Ubuntu, Cantarell, "Open Sans", "Helvetica Neue", sans-serif;
}
html,
body {
   height: 100vh;
   width: 100vw;
}
#threejs-container{
   position: block;
   width: 100%;
   height: 100%;
}
</style>

The above CSS is just the basic stypng of the HTML page. The threejs-container takes up the whole screen.

The JavaScript

This is where our three.js app comes into pfe. The code below renders a single cube in the middle of the screen. All these codes will go into the empty <script> tag in the HTML.


const width = window.innerWidth
const height = window.innerHeight
// Scene
const scene = new THREE.Scene()
scene.background = new THREE.Color( #00b140 )
// Camera
const fov = 45 // AKA Field of View
const aspect = window.innerWidth / window.innerHeight
const near = 0.1 // the near cppping plane
const far = 100 // the far cppping plane
const camera = new PerspectiveCamera(fov, aspect, near, far)
camera.position.set(0, 0, 10)
// Renderer
const renderer = new THREE.WebGLRenderer()
renderer.setSize(window.innerWidth, window.innerHeight)
renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2))
// Creating a cube
const geometry = new THREE.BoxGeometry(2, 2, 2)
const material = new THREE.MeshBasicMaterial({ wireframe: true })
const cube = new THREE.Mesh(geometry, material)
scene.add(cube)
// Rendering the scene
const container = document.querySelector( #threejs-container )
container.append(renderer.domElement)
renderer.render(scene, camera)

Let s discuss the code one step at a time, and then you can get more information about each element in the upcoming chapters. The first thing we need to do is to create a scene, a camera, and a renderer. These are the essential components that make up every Three.js app.

The Scene


const scene = new THREE.Scene()
scene.background = new THREE.Color( #262626 )

The scene serves as the container for everything we can see on the screen, without a THREE.Scene object, Three.js cannot render anything. The background color is dark gray so that we can see the cube.

The Camera


const camera = new PerspectiveCamera(fov, aspect, near, far)
camera.position.set(0, 0, 10)

The camera object defines what we’ll see when we render a scene. There are not many but different types of cameras, but for this example, you’ll use a PerspectiveCamera, which matches the way our eyes see the world.

The Renderer


const renderer = new THREE.WebGLRenderer()
renderer.setSize(window.innerWidth, window.innerHeight)

The renderer object is responsible for calculating what the scene looks pke in the browser, based on the camera. There are different types of renderers, but we mainly use WebGLRenderer since most browsers support WebGL.

In addition to creating the renderer instance, we also need to set the size at which we want it to render our app. It s a good idea to use the width and height of the area we want to fill with our app The Cube- in this case, the width and height of the browser window.

The Cube


const geometry = new THREE.BoxGeometry(2, 2, 2)
const material = new THREE.MeshBasicMaterial({
   color: 0xffffff,
   wireframe: true,
})
const cube = new THREE.Mesh(geometry, material)
scene.add(cube)

The above code creates a simple cube at the center of the screen. We can make any object using THREE.Mesh. The Mesh takes two objects, geometry and material. The geometry of a mesh defines its shape, and materials determine the surface properties of objects.

To create a cube, we need BoxGeometry and a primary material (MeshBasicMaterial) with the color 0xffffff. If the wireframe property is set to true, it tells Three.js to show us a wireframe and not a sopd object.

Rendering the Scene


const container = document.querySelector( #threejs-container )
container.append(renderer.domElement)
renderer.render(scene, camera)

Example

Last but not least, we add the renderer element to our HTML document. The renderer uses an <canvas> element to display the scene to us. In this case, the renderer appends the <canvas> element to the reference container in the HTML.

hello-cube-app.html


<!DOCTYPE html>
<html lang="en">
   <head>
      <meta charset="UTF-8" />
      <meta http-equiv="X-UA-Compatible" content="ie=edge" />
      <meta name="viewport" content="width=device-width, initial-scale=1.0" />
      <title>Three.js – Hello cube</title>
      <style>
         * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
            font-family: -applesystem, BpnkMacSystemFont,  Segoe UI , Roboto, Oxygen, Ubuntu,
            Cantarell,  Open Sans ,  Helvetica Neue , sans-serif;
         }
         html,
         body {
            height: 100vh;
            overflow: hidden;
            width: 100vw;
         }
         #threejs-container {
            position: block;
            width: 100%;
            height: 100%;
         }
      </style>
      <script src="https://cdnjs.cloudflare.com/ajax/pbs/three.js/r128/three.min.js"></script>
   </head>
   <body>
      <span id="threejs-container"></span>
      <script type="module">
         // Hello Cube App
         // Your first Three.js apppcation
         // sizes
         const width = window.innerWidth
         const height = window.innerHeight
         // scene
         const scene = new THREE.Scene()
         scene.background = new THREE.Color(0x262626)
         // camera
         const camera = new THREE.PerspectiveCamera(45, width / height, 0.1, 100)
         camera.position.set(0, 0, 10)
         // cube
         const geometry = new THREE.BoxGeometry(2, 2, 2)
         const material = new THREE.MeshBasicMaterial({
            color: 0xffffff,
            wireframe: true
         })
         const cube = new THREE.Mesh(geometry, material)
         scene.add(cube)
         // renderer
         const renderer = new THREE.WebGL1Renderer()
         renderer.setSize(width, height)
         renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2))
         // rendering the scene
         const container = document.querySelector( #threejs-container )
         container.append(renderer.domElement)
         renderer.render(scene, camera)
      </script>
   </body>
</html>

Output

The output looks pke this if everything is working correctly. Play around with the code to get a better understanding of how it works.