Three.js is a JavaScript library that makes it easy to create 3D animations and visualizations in the browser. To use light in Three.js, you need to create a light object and add it to the scene.
Here are the steps to add light to a scene in Three.js:
1. Import Three.js in your HTML file
2. Create a scene, camera, and renderer
const scene = new THREE.Scene();
const camera = new THREE.PerspectiveCamera(75, window.innerWidth / window.innerHeight, 0.1, 1000);
const renderer = new THREE.WebGLRenderer();
renderer.setSize(window.innerWidth, window.innerHeight);
document.body.appendChild(renderer.domElement);
3. Create a light object
Three.js supports several types of lights including ambient light, directional light, spot light, and point light.
const light = new THREE.PointLight(0xffffff, 1, 100);
light.position.set(10, 10, 10);
scene.add(light);
4. Render the scene
function animate() {
requestAnimationFrame(animate);
renderer.render(scene, camera);
}
animate();
This is a basic example of how to add light to a scene in Three.js. You can experiment with different light types and adjust their properties to achieve the desired lighting effect.
Can I use more than one light source?
Yes, you can use multiple light sources in a Three.js scene. This allows you to create more complex lighting setups and achieve a more natural and realistic look.
Here’s an example of how you could add multiple light sources to a scene in Three.js:
const scene = new THREE.Scene();
const camera = new THREE.PerspectiveCamera(75, window.innerWidth / window.innerHeight, 0.1, 1000);
const renderer = new THREE.WebGLRenderer();
renderer.setSize(window.innerWidth, window.innerHeight);
document.body.appendChild(renderer.domElement);
// Add the first light source
const light1 = new THREE.PointLight(0xffffff, 1, 100);
light1.position.set(10, 10, 10);
scene.add(light1);
// Add the second light source
const light2 = new THREE.DirectionalLight(0xffffff, 1);
light2.position.set(-10, 10, -10);
scene.add(light2);
function animate() {
requestAnimationFrame(animate);
renderer.render(scene, camera);
}
animate();
In this example, we added two light sources to the scene: a PointLight and a DirectionalLight. By using multiple light sources, you can achieve more complex and interesting lighting effects in your Three.js scene.