DEV Community

Krunal Kanojiya
Krunal Kanojiya

Posted on

JavaScript 3D Library - Three.JS with Example

Three.js is a JavaScript library that allows you to create 3D graphics using the JavaScript programming language. It provides a simple and easy-to-use API for creating 3D objects, rendering them to a web page, and animating them.

Here's an example of how you might use Three.js to create a simple 3D cube and render it to a web page:

// First, we need to create a scene
const scene = new THREE.Scene();

// Next, we create a cube and add it to the scene
const geometry = new THREE.BoxGeometry(1, 1, 1);
const material = new THREE.MeshBasicMaterial({ color: 0x00ff00 });
const cube = new THREE.Mesh(geometry, material);
scene.add(cube);

// Then, we create a camera and add it to the scene
const camera = new THREE.PerspectiveCamera(75, window.innerWidth / window.innerHeight, 0.1, 1000);
camera.position.z = 5;

// Next, we create a renderer and set its size
const renderer = new THREE.WebGLRenderer();
renderer.setSize(window.innerWidth, window.innerHeight);

// Finally, we add the renderer's output to the document
document.body.appendChild(renderer.domElement);

// Now, we can render the scene using the renderer
renderer.render(scene, camera);

Enter fullscreen mode Exit fullscreen mode

This code will create a green cube and render it to the web page. You can then use the requestAnimationFrame function to animate the cube by modifying its position, rotation, or other properties.

Three.js also provides a wide range of features for creating more complex 3D graphics, such as lighting, materials, textures, and particle systems. You can learn more about these features in the Three.js documentation.

Top comments (0)