Create Three.js Lens Flare with Directional Light

Adding realistic lens flare effects to a directional light in Three.js enhances the visual depth and realism of your 3D scenes. This guide provides a straightforward, step-by-step tutorial on how to import the necessary Three.js addons, load flare textures, and attach a customizable lens flare effect directly to a directional light source.

1. Import the Required Modules

The lens flare effect is not part of the core Three.js library, so you must import Lensflare and LensflareElement from the examples/addons directory alongside the main Three.js library.

import * as THREE from 'three';
import { Lensflare, LensflareElement } from 'three/addons/objects/Lensflare.js';

2. Set Up the Directional Light

Create a directional light and add it to your scene. This light will serve as the source and anchor point for the lens flare effect.

// Create the directional light (color, intensity)
const directionalLight = new THREE.DirectionalLight(0xffffff, 1.5);
directionalLight.position.set(0, 50, -100);
scene.add(directionalLight);

3. Load Flare Textures

Lens flares require textures (usually simple glow and ring PNG images with black backgrounds) to render the optical artifacts. Use TextureLoader to load these assets.

const textureLoader = new THREE.TextureLoader();

const textureFlare0 = textureLoader.load('path/to/flare0.png'); // Main sun glow
const textureFlare3 = textureLoader.load('path/to/flare3.png'); // Smaller hexagonal artifacts

4. Create and Configure the Lens Flare

Instantiate the Lensflare object. Then, use LensflareElement to define individual flare reflections. Each element takes four parameters: the texture, the size in pixels, the distance from the light source (0.0 to 1.0), and the color.

const lensflare = new Lensflare();

// Add the main light glow at the light source position (distance 0)
lensflare.addElement(new LensflareElement(textureFlare0, 700, 0, directionalLight.color));

// Add smaller secondary flare elements along the light path
lensflare.addElement(new LensflareElement(textureFlare3, 60, 0.6));
lensflare.addElement(new LensflareElement(textureFlare3, 70, 0.7));
lensflare.addElement(new LensflareElement(textureFlare3, 120, 0.9));
lensflare.addElement(new LensflareElement(textureFlare3, 70, 1.0));

5. Attach the Lens Flare to the Light

To ensure the lens flare moves dynamically with your light source, add the lens flare instance directly as a child of the directional light.

directionalLight.add(lensflare);

Whenever the position of the directionalLight changes, the lens flare will automatically update its position in the 3D space.