Atlaslog
Atlaslog / Examples / three.js / Postprocess Volumetric
three.js · Runnable Example

Postprocess Volumetric

Runnable three.js example: Postprocess Volumetric. Open the live demo, read the complete source, and copy the file into your project. No build step or API key.

Open standalone → Chinese notes All three.js examples
/demos/three-postprocess-volumetric.htmlLIVE
single HTML file · CDN dependencies onlyinterface may contain Chinese labels

Source

demos/three-postprocess-volumetric.html
<!--
  说明:以太阳的屏幕位置为中心做径向模糊,得到体积光的散射感
  核心逻辑:自定义 ShaderPass,沿指向光源的方向多次采样并按衰减叠加
  依赖:three.js 0.160.0、OrbitControls、ShaderPass · jsDelivr CDN(ESM + importmap)
-->
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta name="robots" content="noindex,follow">
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>体积光散射</title>
<style>
  html,body{height:100%;margin:0;background:#0a0e0c}
  body{display:flex;flex-direction:column;overflow:hidden;
       font:13px/1.6 -apple-system,"Segoe UI","PingFang SC",sans-serif;color:#e6e8ec}
  .bar{flex:0 0 auto;padding:8px 12px;background:#161b22;border-bottom:1px solid #252c36;
       display:flex;gap:14px;align-items:center;font-size:12px;color:#8b93a1;flex-wrap:wrap}
  .bar b{color:#58a6ff;font-weight:600;font-variant-numeric:tabular-nums}
  .bar input[type=range]{width:120px;accent-color:#4f9ef8}
  .bar .sp{flex:1 1 auto}
  #stage{flex:1 1 auto;min-height:0;position:relative}
  #stage canvas{display:block}
</style>
</head>
<body>
<div class="bar">
  <span>强度 <b id="sv">1.0</b></span>
  <label>光强 <input type="range" id="s" min="0" max="2.4" step="0.1" value="1"></label>
  <span>衰减 <b id="dv">0.94</b></span>
  <label>衰减 <input type="range" id="d" min="0.7" max="0.99" step="0.01" value="0.94"></label>
  <span class="sp"></span>
  <span>拖拽旋转,太阳位置决定散射方向</span>
</div>
<div id="stage"></div>

<script type="importmap">
{
  "imports": {
    "three": "https://cdn.jsdelivr.net/npm/three@0.160.0/build/three.module.js",
    "three/addons/": "https://cdn.jsdelivr.net/npm/three@0.160.0/examples/jsm/"
  }
}
</script>
<script type="module">
import * as THREE from 'three';
import { OrbitControls } from 'three/addons/controls/OrbitControls.js';
import { EffectComposer } from 'three/addons/postprocessing/EffectComposer.js';
import { RenderPass } from 'three/addons/postprocessing/RenderPass.js';
import { ShaderPass } from 'three/addons/postprocessing/ShaderPass.js';
import { OutputPass } from 'three/addons/postprocessing/OutputPass.js';

const stage = document.getElementById('stage');
const renderer = new THREE.WebGLRenderer({ antialias: true });
renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2));
renderer.setSize(stage.clientWidth, stage.clientHeight);
renderer.outputColorSpace = THREE.SRGBColorSpace;
renderer.toneMapping = THREE.ACESFilmicToneMapping;
stage.appendChild(renderer.domElement);

const scene = new THREE.Scene();
scene.background = new THREE.Color(0x121a1c);
scene.fog = new THREE.Fog(0x121a1c, 40, 90);

const camera = new THREE.PerspectiveCamera(45, stage.clientWidth / stage.clientHeight, 0.1, 300);
camera.position.set(18, 11, 26);

const controls = new OrbitControls(camera, renderer.domElement);
controls.target.set(0, 4, 0);
controls.enableDamping = true;
controls.maxPolarAngle = Math.PI * 0.49;
controls.update();

scene.add(new THREE.HemisphereLight(0x9fb8c8, 0x0e1414, 1.0));
const sunLight = new THREE.DirectionalLight(0xffe6b8, 2.4);
sunLight.position.set(14, 16, -30);
scene.add(sunLight);

/* 太阳本体:一块高亮的球,动起来更像低角度阳光 */
const sunBall = new THREE.Mesh(
  new THREE.SphereGeometry(3.2, 24, 16),
  new THREE.MeshBasicMaterial({ color: 0xfff2cc })
);
sunBall.position.copy(sunLight.position).multiplyScalar(1.4);
scene.add(sunBall);

/* 一排剪影状的山脊,散射光从山后透出来 */
function ridge(zPos, scale, color) {
  const shape = new THREE.Shape();
  shape.moveTo(-30, 0);
  for (let i = 0; i <= 30; i++) {
    const x = -30 + i * 2;
    const y = 3 + Math.sin(i * 0.7 + zPos) * 2.2 + Math.cos(i * 0.31) * 1.4;
    shape.lineTo(x, y * scale);
  }
  shape.lineTo(30, 0);
  shape.lineTo(-30, 0);

  const geo = new THREE.ExtrudeGeometry(shape, { depth: 1.2, bevelEnabled: false });
  const mesh = new THREE.Mesh(
    geo,
    new THREE.MeshStandardMaterial({ color: color, roughness: 1, metalness: 0 })
  );
  mesh.position.set(0, 0, zPos);
  scene.add(mesh);
}

ridge(-14, 1.0, 0x2a3640);
ridge(-22, 1.3, 0x1d262e);
ridge(-30, 1.6, 0x141b21);

const ground = new THREE.Mesh(
  new THREE.PlaneGeometry(120, 120),
  new THREE.MeshStandardMaterial({ color: 0x1a2226, roughness: 0.9 })
);
ground.rotation.x = -Math.PI / 2;
scene.add(ground);

/* 径向模糊:从当前像素向光源屏幕位置逐步采样 */
const GodRaysShader = {
  uniforms: {
    tDiffuse: { value: null },
    uLight: { value: new THREE.Vector2(0.5, 0.6) },
    uStrength: { value: 1.0 },
    uDecay: { value: 0.94 },
    uAspect: { value: 1 }
  },
  vertexShader: `
    varying vec2 vUv;
    void main() {
      vUv = uv;
      gl_Position = projectionMatrix * modelViewMatrix * vec4(position, 1.0);
    }
  `,
  fragmentShader: `
    uniform sampler2D tDiffuse;
    uniform vec2 uLight;
    uniform float uStrength;
    uniform float uDecay;
    uniform float uAspect;
    varying vec2 vUv;

    void main() {
      vec4 base = texture2D(tDiffuse, vUv);
      vec2 delta = (uLight - vUv);
      vec2 stepVec = delta / 40.0;
      vec2 coord = vUv;
      float decay = 1.0;
      vec3 acc = vec3(0.0);

      for (int i = 0; i < 40; i++) {
        coord += stepVec;
        vec3 c = texture2D(tDiffuse, coord).rgb;
        /* 只让足够亮的像素贡献散射,暗部不参与 */
        float bright = max(max(c.r, c.g), c.b);
        acc += c * smoothstep(0.55, 0.95, bright) * decay;
        decay *= uDecay;
      }

      acc /= 40.0;
      /* 离光源越近散射越强,用距离做一次软衰减 */
      float d = length((vUv - uLight) * vec2(uAspect, 1.0));
      float falloff = smoothstep(1.2, 0.0, d);
      gl_FragColor = vec4(base.rgb + acc * uStrength * (0.4 + falloff), base.a);
    }
  `
};

const composer = new EffectComposer(renderer);
composer.setSize(stage.clientWidth, stage.clientHeight);
composer.addPass(new RenderPass(scene, camera));

const raysPass = new ShaderPass(GodRaysShader);
raysPass.uniforms.uAspect.value = stage.clientWidth / stage.clientHeight;
composer.addPass(raysPass);
composer.addPass(new OutputPass());

const sEl = document.getElementById('s');
const svEl = document.getElementById('sv');
const dEl = document.getElementById('d');
const dvEl = document.getElementById('dv');

sEl.addEventListener('input', function () {
  raysPass.uniforms.uStrength.value = Number(sEl.value);
  svEl.textContent = Number(sEl.value).toFixed(1);
});
dEl.addEventListener('input', function () {
  raysPass.uniforms.uDecay.value = Number(dEl.value);
  dvEl.textContent = Number(dEl.value).toFixed(2);
});

const tmp = new THREE.Vector3();

function updateLightScreenPos() {
  tmp.copy(sunBall.position).project(camera);
  /* 投影结果在 -1..1,换算到 UV */
  raysPass.uniforms.uLight.value.set(tmp.x * 0.5 + 0.5, tmp.y * 0.5 + 0.5);
}

renderer.setAnimationLoop(function () {
  /* 让太阳缓慢横移,散射方向跟着变化 */
  const t = performance.now() * 0.0001;
  sunBall.position.x = 18 + Math.sin(t) * 26;
  sunLight.position.copy(sunBall.position).multiplyScalar(0.7);

  controls.update();
  updateLightScreenPos();
  composer.render();
});

window.addEventListener('resize', function () {
  const w = stage.clientWidth;
  const h = stage.clientHeight;
  camera.aspect = w / h;
  camera.updateProjectionMatrix();
  renderer.setSize(w, h);
  composer.setSize(w, h);
  raysPass.uniforms.uAspect.value = w / h;
});
</script>
</body>
</html>
Language: the code and this page are in English; the full tutorial and API notes for this example are in Chinese. The demo itself is the authoritative version — it runs exactly as shown.

More three.js examples

three.js · EXAMPLERaycast three.js · EXAMPLERaycaster Texture three.js · EXAMPLEShadow