Three.js online editor

Write, Run & Share Three.js code online using OneCompiler's Three.js online editor for free. It's one of the robust, feature-rich online editors for Three.js. Getting started with the OneCompiler's Three.js online editor is really simple and pretty fast. The editor shows sample boilerplate code when you choose language as 'Three.js' and start writing code to learn and test online without worrying about tedious process of installation.

About Three.js

Three.js is a JavaScript library for drawing 3D graphics in the browser with WebGL. You build a scene, add a camera and some objects, then render frames to a canvas. It handles the heavy lifting (matrices, lighting, materials) so you describe what's in the scene rather than talking to WebGL directly.

Syntax help

Setup

Three.js ships as an ES module. In the editor, import it from a CDN inside a module script and append the renderer's canvas to the page.

import * as THREE from 'https://esm.sh/[email protected]';

Scene, camera, renderer

These three objects are the core of every Three.js app. The scene holds your objects, the camera defines the viewpoint, and the renderer draws it to a canvas.

const scene = new THREE.Scene();

const camera = new THREE.PerspectiveCamera(
  70,                                  // field of view
  window.innerWidth / window.innerHeight, // aspect ratio
  0.1,                                 // near plane
  100                                  // far plane
);
camera.position.z = 3;

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

Meshes

A mesh is a geometry (its shape) paired with a material (how it looks). Add it to the scene to make it visible.

const geometry = new THREE.BoxGeometry();
const material = new THREE.MeshStandardMaterial({ color: '#5c6ac4' });
const cube = new THREE.Mesh(geometry, material);
scene.add(cube);

Lights

MeshStandardMaterial reacts to light, so without a light source it shows up black. Add a directional light for shape and an ambient light to lift the shadows.

const sun = new THREE.DirectionalLight('#ffffff', 2.5);
sun.position.set(2, 2, 3);
scene.add(sun);
scene.add(new THREE.AmbientLight('#ffffff', 0.5));

The animation loop

requestAnimationFrame calls your function before each repaint. Update object properties there and render a fresh frame.

function animate() {
  requestAnimationFrame(animate);
  cube.rotation.x += 0.01;
  cube.rotation.y += 0.01;
  renderer.render(scene, camera);
}
animate();

Handling resize

Keep the camera's aspect ratio and the renderer's size in sync with the window so the scene doesn't stretch.

window.addEventListener('resize', () => {
  camera.aspect = window.innerWidth / window.innerHeight;
  camera.updateProjectionMatrix();
  renderer.setSize(window.innerWidth, window.innerHeight);
});