Implementing Realistic Refraction in Three.js | Creating Glass‑Like Effects
Do you want to create a transparent, glass‑like refraction effect in Three.js?
This article explains how refraction mapping works using a CubeCamera, and how to implement realistic refractive materials.
By using a CubeCamera (six cameras rendering in six directions to a WebGLCubeRenderTarget), you can create materials that simulate glass‑like refraction and apply them to your meshes.
Rotate with left mouse drag, move the camera with right mouse drag, and zoom with the mouse wheel.
On touch devices: swipe to rotate, drag with two fingers to move the camera, and pinch in/out to zoom.
Source Code
// Create a render target for refraction mapping
cubeRenderTargetRefraction = new THREE.WebGLCubeRenderTarget(512, {
generateMipmaps: true,
minFilter: THREE.LinearMipmapLinearFilter,
});
cubeRenderTargetRefraction.texture.mapping = THREE.CubeRefractionMapping; // Set to refraction mapping
cubeRenderTargetRefraction.texture.type = THREE.HalfFloatType;
// Create a CubeCamera for refraction mapping
// (near clipping distance, far clipping distance, render target)
cubeCameraRefraction = new THREE.CubeCamera(0.1, 10000, cubeRenderTargetRefraction);
// scene.add(cubeCameraRefraction);
// Create a Lambert material for refraction (non‑glossy material affected by lights)
let materialRefraction = new THREE.MeshLambertMaterial({
color: 0xffffff,
envMap: cubeCameraRefraction.renderTarget.texture,
opacity: 1.0,
refractionRatio: 0.6, // Index of refraction
// side: THREE.DoubleSide,
side: THREE.FrontSide,
transparent: true,
combine: THREE.MixOperation,
// combine: THREE.AddOperation,
});
// Create a sphere geometry (radius, width segments, height segments, phiStart, phiLength)
let sphereGeometry = new THREE.SphereGeometry(20, 32, 16, 0, Math.PI * 2);
// Create the refractive mesh from geometry and material
meshRefraction = new THREE.Mesh(sphereGeometry, materialRefraction);
meshRefraction.position.set(0, 0, 0);
scene.add(meshRefraction); // Add mesh to the scene
cubeCameraRefraction.position.copy(meshRefraction.position); // Set CubeCamera position
Back to the list of 3D JavaScript content
