Atlaslog
Atlaslog / Examples / three.js / Shadow
three.js · Runnable Example

Shadow

Runnable three.js example: Shadow. 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-shadow.htmlLIVE
single HTML file · CDN dependencies onlyinterface may contain Chinese labels

Source

demos/three-shadow.html
<!--
  说明:同一盏平行光下切换阴影开关、贴图分辨率与偏置,观察阴影粉刺和漏光的变化
  核心逻辑:DirectionalLight.castShadow 配合阴影相机的正交范围与 mapSize,控制投影质量
  依赖:three.js 0.160.0、OrbitControls · 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:#0d1117}
  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:12px;align-items:center;font-size:12px;color:#8b93a1;flex-wrap:wrap}
  .bar b{color:#58a6ff;font-weight:600}
  .bar input[type=range]{width:120px;accent-color:#4f9ef8}
  .bar button{font:inherit;font-size:12px;padding:4px 10px;border-radius:5px;cursor:pointer;
       border:1px solid #303845;background:#1d2531;color:#c8d2e0}
  .bar button:hover{background:#253040}
  .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="state">开</b></span>
  <button id="toggle">关闭阴影</button>
  <button id="type">贴图:PCFSoft</button>
  <button id="size">分辨率:1024</button>
  <label>法线偏置 <input type="range" id="bias" min="0" max="0.2" step="0.005" value="0.04"></label>
  <span><b id="biasv">0.040</b></span>
  <button id="helper">显示阴影相机</button>
  <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';

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;
renderer.toneMappingExposure = 1.0;
renderer.shadowMap.enabled = true;
renderer.shadowMap.type = THREE.PCFSoftShadowMap;
stage.appendChild(renderer.domElement);

const scene = new THREE.Scene();
scene.background = new THREE.Color(0x0b1016);
scene.fog = new THREE.Fog(0x0b1016, 70, 170);

const camera = new THREE.PerspectiveCamera(
  42, stage.clientWidth / stage.clientHeight, 0.5, 260
);
camera.position.set(52, 40, 58);

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

scene.add(new THREE.HemisphereLight(0xbcd8ff, 0x16202a, 0.85));

const sun = new THREE.DirectionalLight(0xfff0d8, 2.6);
sun.position.set(-48, 60, 34);
sun.castShadow = true;
sun.shadow.mapSize.set(1024, 1024);
sun.shadow.normalBias = 0.04;
sun.shadow.camera.left = -52;
sun.shadow.camera.right = 52;
sun.shadow.camera.top = 52;
sun.shadow.camera.bottom = -52;
sun.shadow.camera.near = 1;
sun.shadow.camera.far = 180;
sun.shadow.camera.updateProjectionMatrix();
scene.add(sun);
scene.add(sun.target);

/* 太阳位置的示意球 */
const sunDot = new THREE.Mesh(
  new THREE.SphereGeometry(1.2, 16, 12),
  new THREE.MeshBasicMaterial({ color: 0xffd27a })
);
sunDot.position.copy(sun.position);
scene.add(sunDot);

const ground = new THREE.Mesh(
  new THREE.PlaneGeometry(140, 140),
  new THREE.MeshStandardMaterial({ color: 0x18222c, roughness: 0.96 })
);
ground.rotation.x = -Math.PI / 2;
ground.receiveShadow = true;
scene.add(ground);

/* 两排高低不同的楼,用来观察阴影的长短与贴合情况 */
const boxGeo = new THREE.BoxGeometry(6, 1, 6);
boxGeo.translate(0, 0.5, 0);

for (let gx = -3; gx <= 3; gx++) {
  for (let gz = -2; gz <= 2; gz++) {
    if (Math.abs(gx) + Math.abs(gz) > 4) continue;

    const h = 5 + ((gx * 7 + gz * 13 + 40) % 9) * 2.2;
    const mesh = new THREE.Mesh(
      boxGeo,
      new THREE.MeshStandardMaterial({
        color: new THREE.Color().setHSL(0.56, 0.16, 0.42),
        roughness: 0.8
      })
    );
    mesh.position.set(gx * 13, 0, gz * 13);
    mesh.scale.set(1, h, 1);
    mesh.castShadow = true;
    mesh.receiveShadow = true;
    scene.add(mesh);
  }
}

/* 阴影相机辅助线 */
const helper = new THREE.CameraHelper(sun.shadow.camera);
helper.visible = false;
scene.add(helper);

const stateEl = document.getElementById('state');
const toggleBtn = document.getElementById('toggle');
const typeBtn = document.getElementById('type');
const sizeBtn = document.getElementById('size');
const biasInput = document.getElementById('bias');
const biasv = document.getElementById('biasv');
const helperBtn = document.getElementById('helper');

toggleBtn.addEventListener('click', function () {
  sun.castShadow = !sun.castShadow;
  stateEl.textContent = sun.castShadow ? '开' : '关';
  toggleBtn.textContent = sun.castShadow ? '关闭阴影' : '开启阴影';
});

/* 换阴影类型需要让所有材质重新编译着色器 */
function setShadowType(type, label) {
  renderer.shadowMap.type = type;
  scene.traverse(function (obj) {
    if (!obj.material) return;
    const list = Array.isArray(obj.material) ? obj.material : [obj.material];
    list.forEach(function (m) { m.needsUpdate = true; });
  });
  typeBtn.textContent = '贴图:' + label;
}

const types = [
  { type: THREE.PCFSoftShadowMap, label: 'PCFSoft' },
  { type: THREE.PCFShadowMap, label: 'PCF' },
  { type: THREE.BasicShadowMap, label: 'Basic' }
];
let typeIndex = 0;

typeBtn.addEventListener('click', function () {
  typeIndex = (typeIndex + 1) % types.length;
  setShadowType(types[typeIndex].type, types[typeIndex].label);
});

const sizes = [1024, 2048, 4096];
let sizeIndex = 0;

sizeBtn.addEventListener('click', function () {
  sizeIndex = (sizeIndex + 1) % sizes.length;
  const s = sizes[sizeIndex];
  sun.shadow.mapSize.set(s, s);

  /* 已有阴影贴图必须先释放,否则新尺寸不会生效 */
  if (sun.shadow.map) {
    sun.shadow.map.dispose();
    sun.shadow.map = null;
  }
  sizeBtn.textContent = '分辨率:' + s;
});

biasInput.addEventListener('input', function () {
  sun.shadow.normalBias = Number(biasInput.value);
  biasv.textContent = sun.shadow.normalBias.toFixed(3);
});

helperBtn.addEventListener('click', function () {
  helper.visible = !helper.visible;
  helperBtn.textContent = helper.visible ? '隐藏阴影相机' : '显示阴影相机';
});

renderer.setAnimationLoop(function () {
  controls.update();
  if (helper.visible) helper.update();
  renderer.render(scene, camera);
});

window.addEventListener('resize', function () {
  const w = stage.clientWidth;
  const h = stage.clientHeight;
  camera.aspect = w / h;
  camera.updateProjectionMatrix();
  renderer.setSize(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 · EXAMPLEShadow Pointlight three.js · EXAMPLEShadow Viewer three.js · EXAMPLEShadow Vsm