Blog>
Snippets

Initializing a Three.js Scene

Set up the basic elements required for any Three.js application: scene, camera, and renderer. Add a simple geometry and render it.
// Create a scene
const scene = new THREE.Scene();
This line initializes a new Three.js scene object.
// Set up a camera
const camera = new THREE.PerspectiveCamera(75, window.innerWidth / window.innerHeight, 0.1, 1000);
camera.position.set(0, 0, 5);
This initializes a perspective camera with a field of view of 75 degrees, an aspect ratio based on the browser window size, and near and far clipping planes. The camera is positioned 5 units along the Z axis.
// Create a renderer and add it to the DOM
const renderer = new THREE.WebGLRenderer();
renderer.setSize(window.innerWidth, window.innerHeight);
document.body.appendChild(renderer.domElement);
This creates a WebGL renderer, sets its size to fill the browser window, and then appends the renderer's canvas element to the document's body.
// Add a simple geometry and material
const geometry = new THREE.BoxGeometry();
const material = new THREE.MeshBasicMaterial({ color: 0x00ff00 });
const cube = new THREE.Mesh(geometry, material);
scene.add(cube);
This creates a simple box geometry and a basic material with a green color. It then creates a mesh by combining the geometry and material, and adds the mesh to the scene.
// Animation loop
function animate() {
    requestAnimationFrame(animate);
    renderer.render(scene, camera);
}

animate();
This defines an animation loop function that will be called repeatedly by requestAnimationFrame. Inside the function, the scene is rendered from the perspective of the camera.