Language: EN

three-js

Three.js, WebGL library for creating 3D graphics

Three.js is a JavaScript library that allows you to create interactive 3D content for the web. It uses WebGL, which is an API that allows web browsers to display 3D content using hardware acceleration on the GPU.

Three.js offers a wide range of functionalities for interacting with the scene, such as the ability to load 3D models from files like OBJ or STL, apply transformations and animations, and add light and shadows.

We can also apply transformations and animations, modify the position, rotation, and scale of your objects using their corresponding geometry properties, and add light and shadows.

How to use ThreeJS

To install Three.js, there are several options available. One option is to download the distribution file from the official Three.js website and then include it in your project using a link in the “script” element of your HTML page, or through a CDN,

<script src="js/three.min.js"></script>

You can also use a package manager like npm to install Three.js and then import it into your project:

npm install three

And then import the module into your program

import * as THREE from 'three';

ThreeJS Example

Below is a simple example of how to initialize ThreeJS, showing a simple rotating cube in space. The necessary code would be as follows,

<!DOCTYPE html>
<html>
<body>
    <script src="https://cdn.jsdelivr.net/npm/three@0.152.2/build/three.min.js"></script>
    <script src="app.js"></script>
</body>
</html>
let camera, scene, renderer, cube

function init () {
  camera = new THREE.PerspectiveCamera( 70, window.innerWidth / window.innerHeight, 0.01, 10 )
  camera.position.z = 1

  scene = new THREE.Scene()

  const geometry = new THREE.BoxGeometry(0.5, 0.5, 0.5)
  const material = new THREE.MeshNormalMaterial()

  cube = new THREE.Mesh(geometry, material)
  scene.add(cube)

  renderer = new THREE.WebGLRenderer({ antialias: true })
  renderer.setSize(window.innerWidth, window.innerHeight)
  document.body.appendChild(renderer.domElement)

  animate()
}

function animate () {
  requestAnimationFrame(animate)

  cube.rotation.x += 0.01
  cube.rotation.y += 0.01

  renderer.render(scene, camera)
}

init()

Result

With the above code we would get this result

ThreeJS is Open Source, and all the code and documentation is available on the project page https://threejs.org/ and in the project repository at https://github.com/mrdoob/three.js/