Frosted Glass
透過有細緻紋理的霧面玻璃看見枝葉,移動光斑觀察玻璃的反射。

正在載入 3D 場景…
用 Three.js 製作霧面玻璃
從枝葉模型開始,再把光線與玻璃紋理加到畫面上。每一步都附有程式碼,頁尾可展開查看 demo 的原始檔。
安裝 Three.js
在 Nuxt 專案中加入 Three.js 和對應的 TypeScript 型別。
bun add three@0.187.0 bun add -d @types/three@0.187.0建立枝條和葉片
用貝茲曲線決定枝條形狀,再用 InstancedMesh 沿著曲線重複使用同一片彎曲葉片。完整的 leafGeometry() 在 garden.ts 裡。
const stem = new THREE.QuadraticBezierCurve3( new THREE.Vector3(3.8, -2.9, -1.2), new THREE.Vector3(0.8, -1.5, -0.7), new THREE.Vector3(0.2, 0.45, -1.55), ); garden.add(new THREE.Mesh( new THREE.TubeGeometry(stem, 22, 0.014, 5, false), new THREE.MeshStandardMaterial({ color: 0x415028 }), )); const count = 18; const leaves = new THREE.InstancedMesh( leafGeometry(), new THREE.MeshStandardMaterial({ side: THREE.DoubleSide, vertexColors: true, }), count, ); const leaf = new THREE.Object3D(); for (let i = 0; i < count; i++) { const t = (i + 1) / (count + 1); leaf.position.copy(stem.getPoint(t)); leaf.rotation.z = i % 2 ? -1.1 : 1.1; leaf.scale.setScalar(0.54 - t * 0.22); leaf.updateMatrix(); leaves.setMatrixAt(i, leaf.matrix); } garden.add(leaves);把枝葉渲染成紋理
先將枝葉場景畫進 WebGLRenderTarget,再透過 uGarden 把紋理傳給玻璃的 ShaderMaterial。第二次渲染才會畫到畫布上。
const gardenTarget = new THREE.WebGLRenderTarget(width, height); const glassMaterial = new THREE.ShaderMaterial({ uniforms: { uGarden: { value: gardenTarget.texture }, uLight: { value: new THREE.Vector2(0.24, 0.73) }, uAspect: { value: width / height }, }, vertexShader: glassVertex, fragmentShader: glassFragment, }); const pane = new THREE.Scene(); pane.add(new THREE.Mesh(new THREE.PlaneGeometry(32, 24), glassMaterial)); function draw() { renderer.setRenderTarget(gardenTarget); renderer.render(garden, camera); renderer.setRenderTarget(null); renderer.render(pane, camera); }加入霧面紋理與反光
從表面的細小起伏求出斜率,據此偏移並模糊紋理取樣。斜率也會改變反光的方向。relief() 和 frostedSample() 的完整程式碼在 shaders.ts 裡。
vec2 uv = (vScreen.xy / vScreen.w) * 0.5 + 0.5; float height = relief(vSurface); vec2 slope = vec2( relief(vSurface + vec2(0.004, 0.0)), relief(vSurface + vec2(0.0, 0.004)) ) - height; vec2 scale = vec2(1.0 / uAspect, 1.0); vec2 distortion = slope * 0.036 * scale; vec3 color = frostedSample(uv + distortion, scale * 0.022); vec3 normal = normalize(vec3(-slope * 1.6, 1.0)); vec2 lightDelta = (uLight - uv) * vec2(uAspect, 1.0); vec3 halfVector = normalize(vec3(lightDelta * 1.75, 1.0)); float reflection = pow(max(dot(normal, halfVector), 0.0), 27.0); gl_FragColor = vec4(color + vec3(reflection * 0.55), 1.0); #include <colorspace_fragment>將指標位置傳給光斑
把 pointermove 和 pointerdown 綁到 onPointer,將指標座標轉成 0 到 1 的範圍。元件卸載時釋放場景資源。
import { createGlassScene } from "./scene"; const viewport = useTemplateRef<HTMLDivElement>("viewport"); const canvas = useTemplateRef<HTMLCanvasElement>("canvas"); let demo: ReturnType<typeof createGlassScene> | undefined; let observer: ResizeObserver | undefined; onMounted(() => { const surface = viewport.value; if (!canvas.value || !surface) return; const scene = createGlassScene(canvas.value); demo = scene; scene.resize(surface.clientWidth, surface.clientHeight); observer = new ResizeObserver(() => { scene.resize(surface.clientWidth, surface.clientHeight); }); observer.observe(surface); }); function onPointer(event: PointerEvent) { const bounds = viewport.value?.getBoundingClientRect(); if (!bounds?.width || !bounds.height) return; const x = (event.clientX - bounds.left) / bounds.width; const y = 1 - (event.clientY - bounds.top) / bounds.height; const reducedMotion = matchMedia("(prefers-reduced-motion: reduce)"); demo?.moveLight(x, y, reducedMotion.matches); } onBeforeUnmount(() => { observer?.disconnect(); demo?.dispose(); });
Demo 原始碼
garden.ts
import * as THREE from "three";
import { backdropFragment, backdropVertex } from "./shaders";
function leafGeometry() {
const positions: number[] = [];
const colors: number[] = [];
const indices: number[] = [];
const rows = 18;
const columns = 10;
for (let row = 0; row <= rows; row++) {
const length = row / rows;
const width = 0.32 * Math.pow(Math.sin(Math.PI * length), 0.82) * (1.17 - length * 0.38);
for (let column = 0; column <= columns; column++) {
const side = column / columns * 2 - 1;
const edge = Math.abs(side);
const ribs = Math.sin((length - edge * 0.14) * 42.0);
const x = side * width * (1 + ribs * edge * 0.06) + 0.05 * length * length;
const z = Math.sin(length * Math.PI) * (0.11 - 0.19 * edge * edge)
+ 0.035 * side * length + 0.16 * Math.pow(length, 4);
const vein = Math.exp(-edge * 34) * 0.22 + Math.pow(Math.max(ribs, 0), 8) * 0.06;
positions.push(x, length, z);
colors.push(0.62 + vein, 0.78 + vein, 0.42 + vein * 0.55);
if (row < rows && column < columns) {
const a = row * (columns + 1) + column;
const b = a + columns + 1;
indices.push(a, a + 1, b, b, a + 1, b + 1);
}
}
}
const geometry = new THREE.BufferGeometry();
geometry.setAttribute("position", new THREE.Float32BufferAttribute(positions, 3));
geometry.setAttribute("color", new THREE.Float32BufferAttribute(colors, 3));
geometry.setIndex(indices);
geometry.computeVertexNormals();
return geometry;
}
const branches = [
[[3.8, -2.9, -1.2], [0.8, -1.5, -0.7], [0.2, 0.45, -1.55]],
[[3.5, -2.7, -0.95], [2.1, -0.25, -1.2], [2.6, 1.9, -1.8]],
[[4.0, -1.0, -1.7], [2.5, 0.8, -1.9], [0.9, 1.65, -2.4]],
[[1.1, -3.0, -0.75], [0.7, -1.45, -0.9], [-0.7, -0.6, -1.55]],
[[2.2, -3.2, -1.2], [0.55, -2.2, -1.1], [-1.2, -1.8, -1.3]],
[[4.4, -2.1, -1.35], [3.0, 0.3, -1.0], [3.25, 2.8, -1.9]],
[[-3.6, -2.8, -3.2], [-2.3, -1.0, -2.9], [-1.35, 1.5, -3.6]],
[[-2.7, -3.3, -3.3], [-0.45, -1.65, -3.55], [-0.3, 1.9, -3.7]],
[[2.2, -3.4, -3.4], [2.1, -0.8, -3.5], [1.8, 2.5, -4.1]],
[[4.9, -0.9, -3.7], [2.6, 0.5, -3.8], [2.7, 3.2, -4.4]],
[[0.55, -3.2, -0.45], [0.95, -2.1, -0.65], [0.75, -1.2, -0.7]],
[[3.5, -2.9, -0.65], [2.0, -1.7, -0.55], [1.28, -1.3, -0.65]],
] as const;
export function createGarden() {
const scene = new THREE.Scene();
const backdrop = new THREE.Mesh(
new THREE.PlaneGeometry(36, 26),
new THREE.ShaderMaterial({ vertexShader: backdropVertex, fragmentShader: backdropFragment }),
);
backdrop.position.z = -6;
scene.add(backdrop);
const canopy = new THREE.Group();
scene.add(canopy, new THREE.HemisphereLight(0xf2ffd7, 0x193423, 1.45));
const sun = new THREE.DirectionalLight(0xffefc3, 2.5);
sun.position.set(-3.8, 4.2, 3);
const fill = new THREE.DirectionalLight(0xadc775, 0.8);
fill.position.set(3, 1, -3);
scene.add(sun, fill);
const leavesPerBranch = 18;
const leaves = new THREE.InstancedMesh(
leafGeometry(),
new THREE.MeshStandardMaterial({ side: THREE.DoubleSide, vertexColors: true, roughness: 0.57 }),
branches.length * leavesPerBranch,
);
const stemMaterial = new THREE.MeshStandardMaterial({ color: 0x415028, roughness: 0.88 });
const leaf = new THREE.Object3D();
const palette = [0x487e24, 0x639630, 0x85a234, 0x2d5725, 0x86a846, 0x3d712a].map((color) => new THREE.Color(color));
const color = new THREE.Color();
let seed = 529;
const random = () => {
seed = (Math.imul(seed, 1664525) + 1013904223) >>> 0;
return seed / 4294967296;
};
branches.forEach(([start, bend, end], branchIndex) => {
const curve = new THREE.QuadraticBezierCurve3(
new THREE.Vector3(...start),
new THREE.Vector3(...bend),
new THREE.Vector3(...end),
);
canopy.add(new THREE.Mesh(new THREE.TubeGeometry(curve, 22, 0.014, 5, false), stemMaterial));
for (let index = 0; index < leavesPerBranch; index++) {
const progress = 0.10 + (index + random()) * 0.9 / leavesPerBranch;
const side = index % 2 ? -1 : 1;
const size = (0.33 + random() * 0.47) * (1 - progress * 0.42);
leaf.position.copy(curve.getPoint(progress));
leaf.rotation.set(
(random() - 0.5) * 1.75,
(random() - 0.5) * 1.8,
side * (0.53 + random() * 1.6) + (random() - 0.5) * 0.5,
);
leaf.scale.set(size * (0.8 + random() * 0.65), size, size);
leaf.updateMatrix();
const instance = branchIndex * leavesPerBranch + index;
leaves.setMatrixAt(instance, leaf.matrix);
color.copy(palette[Math.floor(random() * palette.length)]!).multiplyScalar(0.76 + random() * 0.58);
leaves.setColorAt(instance, color);
}
});
canopy.add(leaves);
return { scene, canopy };
}
scene.ts
import * as THREE from "three";
import { createGarden } from "./garden";
import { glassFragment, glassVertex } from "./shaders";
export const defaultLight = { x: 0.24, y: 0.73 } as const;
export function createGlassScene(canvas: HTMLCanvasElement) {
const renderer = new THREE.WebGLRenderer({ canvas, alpha: false, antialias: false });
const camera = new THREE.PerspectiveCamera(36, 1, 0.1, 40);
const { scene: garden, canopy } = createGarden();
const pane = new THREE.Scene();
const gardenTarget = new THREE.WebGLRenderTarget(1, 1, {
minFilter: THREE.LinearFilter,
magFilter: THREE.LinearFilter,
type: renderer.extensions.has("EXT_color_buffer_float") ? THREE.HalfFloatType : THREE.UnsignedByteType,
});
const uniforms = {
uGarden: { value: gardenTarget.texture },
uLight: { value: new THREE.Vector2(defaultLight.x, defaultLight.y) },
uAspect: { value: 1 },
};
const glass = new THREE.Mesh(
new THREE.PlaneGeometry(32, 24),
new THREE.ShaderMaterial({ uniforms, vertexShader: glassVertex, fragmentShader: glassFragment }),
);
pane.add(glass);
const target = new THREE.Vector2(defaultLight.x, defaultLight.y);
const light = uniforms.uLight.value;
let showGlass = true;
let frame = 0;
function draw() {
const offsetX = light.x - defaultLight.x;
const offsetY = light.y - defaultLight.y;
camera.position.set(offsetX * 0.87, offsetY * 0.54, 7);
camera.lookAt(0, 0, 0);
canopy.rotation.set(offsetY * 0.025, offsetX * 0.045, 0);
if (showGlass) {
renderer.setRenderTarget(gardenTarget);
renderer.render(garden, camera);
renderer.setRenderTarget(null);
}
renderer.render(showGlass ? pane : garden, camera);
}
function animate() {
frame = 0;
if (light.distanceToSquared(target) < 0.000004) {
light.copy(target);
draw();
return;
}
light.lerp(target, 0.21);
draw();
frame = requestAnimationFrame(animate);
}
return {
resize(width: number, height: number) {
if (width <= 0 || height <= 0) return;
const pixelRatio = Math.min(window.devicePixelRatio, 1.5, 1500 / width, 1020 / height);
camera.aspect = width / height;
camera.updateProjectionMatrix();
uniforms.uAspect.value = camera.aspect;
renderer.setDrawingBufferSize(width, height, pixelRatio);
gardenTarget.setSize(
Math.max(1, Math.round(width * pixelRatio * 0.8)),
Math.max(1, Math.round(height * pixelRatio * 0.8)),
);
draw();
},
moveLight(x: number, y: number, immediate: boolean) {
target.set(x, y);
if (immediate) {
cancelAnimationFrame(frame);
frame = 0;
light.copy(target);
draw();
} else if (!frame) {
frame = requestAnimationFrame(animate);
}
},
setGlassVisible(visible: boolean) {
showGlass = visible;
draw();
},
dispose() {
cancelAnimationFrame(frame);
const geometries = new Set<THREE.BufferGeometry>();
const materials = new Set<THREE.Material>();
for (const scene of [garden, pane]) {
scene.traverse((object) => {
if (!(object instanceof THREE.Mesh)) return;
geometries.add(object.geometry);
for (const material of [object.material].flat()) materials.add(material);
if (object instanceof THREE.InstancedMesh) object.dispose();
});
}
geometries.forEach((geometry) => geometry.dispose());
materials.forEach((material) => material.dispose());
gardenTarget.dispose();
renderer.dispose();
},
};
}
shaders.ts
export const glassVertex = /* glsl */ `
varying vec2 vSurface;
varying vec4 vScreen;
void main() {
vSurface = position.xy;
vScreen = projectionMatrix * modelViewMatrix * vec4(position, 1.0);
gl_Position = vScreen;
}
`;
export const glassFragment = /* glsl */ `
uniform sampler2D uGarden;
uniform vec2 uLight;
uniform float uAspect;
varying vec2 vSurface;
varying vec4 vScreen;
float hash(vec2 p) {
vec3 q = fract(vec3(p.xyx) * 0.1031);
q += dot(q, q.yzx + 33.33);
return fract((q.x + q.y) * q.z);
}
float noise(vec2 p) {
vec2 cell = floor(p);
vec2 t = fract(p);
t = t * t * (3.0 - 2.0 * t);
return mix(
mix(hash(cell), hash(cell + vec2(1.0, 0.0)), t.x),
mix(hash(cell + vec2(0.0, 1.0)), hash(cell + vec2(1.0, 1.0)), t.x),
t.y
);
}
float relief(vec2 p) {
return noise(p * 48.0) + 0.38 * noise(p * 132.0 + 41.0) + 0.13 * noise(p * 254.0);
}
vec3 frostedSample(vec2 uv, vec2 radius) {
vec3 color = texture2D(uGarden, uv).rgb * 0.19;
for (int i = 0; i < 12; i++) {
float angle = float(i) * 2.399963;
float distanceFromCenter = sqrt((float(i) + 0.5) / 12.0);
vec2 offset = vec2(cos(angle), sin(angle)) * radius * distanceFromCenter;
color += texture2D(uGarden, uv + offset).rgb * 0.0675;
}
return color;
}
void main() {
vec2 uv = (vScreen.xy / vScreen.w) * 0.5 + 0.5;
float height = relief(vSurface);
vec2 slope = vec2(
relief(vSurface + vec2(0.004, 0.0)),
relief(vSurface + vec2(0.0, 0.004))
) - height;
vec2 screenScale = vec2(1.0 / uAspect, 1.0);
vec2 distortion = (slope * 0.036 + (height - 0.68) * 0.004) * screenScale;
vec3 garden = frostedSample(uv + distortion, screenScale * (0.015 + height * 0.010));
vec3 color = garden * vec3(0.88, 1.05, 0.80) + vec3(0.005, 0.010, 0.004);
// Each bump reflects the light at a slightly different angle.
vec2 lightDelta = (uLight - uv) * vec2(uAspect, 1.0);
vec3 normal = normalize(vec3(-slope * 1.6, 1.0));
vec2 lightShape = lightDelta * vec2(0.94, 0.80);
vec3 halfVector = normalize(vec3(lightShape * 1.75, 1.0));
float specular = pow(max(dot(normal, halfVector), 0.0), 27.0);
float glow = exp(-dot(lightShape, lightShape) * 7.0);
float softReflection = exp(-dot(lightShape, lightShape) * 3.8);
color += vec3(1.0, 0.98, 0.91) * (0.83 * specular * glow + 0.18 * softReflection);
color *= 0.90 + height * 0.16;
// The embedded wire grid sits just below the textured surface.
vec2 wireCoord = (vSurface + slope * 0.012) / 0.078;
vec2 wireDistance = abs(fract(wireCoord - 0.5) - 0.5);
vec2 wireWidth = fwidth(wireCoord);
vec2 wire = 1.0 - smoothstep(vec2(0.01), vec2(0.026) + wireWidth * 0.38, wireDistance);
color += max(wire.x, wire.y) * vec3(0.033, 0.045, 0.027) * (1.0 - glow * 0.65);
float vignette = 1.0 - 0.30 * dot(uv - 0.5, uv - 0.5);
gl_FragColor = vec4(color * vignette, 1.0);
#include <colorspace_fragment>
}
`;
export const backdropVertex = /* glsl */ `
varying vec2 vBackdrop;
void main() {
vBackdrop = position.xy;
gl_Position = projectionMatrix * modelViewMatrix * vec4(position, 1.0);
}
`;
export const backdropFragment = /* glsl */ `
varying vec2 vBackdrop;
void main() {
vec2 p = vBackdrop;
vec2 beam = vec2((p.x + 3.5 - 0.22 * p.y) * 0.27, (p.y - 1.9) * 0.15);
float daylight = exp(-dot(beam, beam) * 1.9);
vec2 bounce = (p - vec2(1.9, -2.7)) * vec2(0.25, 0.36);
float bounceLight = exp(-dot(bounce, bounce) * 1.5);
vec3 color = vec3(0.008, 0.016, 0.009);
color += vec3(0.34, 0.40, 0.23) * daylight;
color += vec3(0.018, 0.065, 0.010) * bounceLight;
gl_FragColor = vec4(color, 1.0);
#include <colorspace_fragment>
}
`;
Demo.vue
<script setup lang="ts">
import { frostedGlassPoster, type frostedGlassContent } from "./data";
import type { createGlassScene } from "./scene";
defineProps<{
labels: (typeof frostedGlassContent)[keyof typeof frostedGlassContent];
}>();
const viewport = useTemplateRef<HTMLDivElement>("viewport");
const canvas = useTemplateRef<HTMLCanvasElement>("canvas");
const hintId = useId();
const status = ref<"loading" | "ready" | "unavailable">("loading");
const glassVisible = ref(true);
const arrowOffsets = {
ArrowLeft: [-1, 0],
ArrowRight: [1, 0],
ArrowUp: [0, 1],
ArrowDown: [0, -1],
} as const;
let scene: ReturnType<typeof createGlassScene> | undefined;
let resizeObserver: ResizeObserver | undefined;
let reducedMotion: MediaQueryList;
let position = { x: 0, y: 0 };
let unmounted = false;
function stopScene() {
resizeObserver?.disconnect();
scene?.dispose();
scene = undefined;
}
function showFallback() {
status.value = "unavailable";
stopScene();
}
function moveLight(x: number, y: number) {
if (!scene) return;
position.x = Math.min(1, Math.max(0, x));
position.y = Math.min(1, Math.max(0, y));
scene.moveLight(position.x, position.y, reducedMotion.matches);
}
function onPointer(event: PointerEvent) {
if (!scene || !event.isPrimary || (event.pointerType !== "mouse" && event.buttons === 0)) return;
const bounds = viewport.value?.getBoundingClientRect();
if (!bounds?.width || !bounds.height) return;
moveLight((event.clientX - bounds.left) / bounds.width, 1 - (event.clientY - bounds.top) / bounds.height);
}
function onKeydown(event: KeyboardEvent) {
if (!scene || !Object.hasOwn(arrowOffsets, event.key)) return;
const [x, y] = arrowOffsets[event.key as keyof typeof arrowOffsets];
event.preventDefault();
moveLight(position.x + x * 0.065, position.y + y * 0.065);
}
function toggleGlass() {
if (!scene) return;
glassVisible.value = !glassVisible.value;
scene.setGlassVisible(glassVisible.value);
}
onMounted(async () => {
try {
const { createGlassScene, defaultLight } = await import("./scene");
if (unmounted || !canvas.value || !viewport.value) return;
const surface = viewport.value;
reducedMotion = window.matchMedia("(prefers-reduced-motion: reduce)");
position = { ...defaultLight };
scene = createGlassScene(canvas.value);
scene.resize(surface.clientWidth, surface.clientHeight);
resizeObserver = new ResizeObserver(([entry]) => {
if (entry) scene?.resize(entry.contentRect.width, entry.contentRect.height);
});
resizeObserver.observe(surface);
status.value = "ready";
} catch {
if (!unmounted) showFallback();
}
});
onBeforeUnmount(() => {
unmounted = true;
stopScene();
});
</script>
<template>
<figure class="overflow-hidden rounded-2xl border border-border bg-card">
<div
ref="viewport"
class="relative aspect-square overflow-hidden bg-[#202c1c] focus-visible:outline-2 focus-visible:-outline-offset-4 focus-visible:outline-white sm:aspect-[8/5]"
:class="{ 'cursor-crosshair touch-pan-y touch-pinch-zoom': status === 'ready' }"
role="group"
:aria-label="labels.sceneLabel"
:aria-describedby="hintId"
:tabindex="status === 'ready' ? 0 : undefined"
@pointermove="onPointer"
@pointerdown="onPointer"
@keydown="onKeydown"
>
<img
:src="frostedGlassPoster"
alt=""
width="1080"
height="675"
class="absolute inset-0 size-full object-cover"
/>
<canvas
ref="canvas"
class="absolute inset-0 block size-full"
:class="{ invisible: status !== 'ready' }"
aria-hidden="true"
@webglcontextlost="showFallback"
/>
</div>
<figcaption class="flex min-h-16 flex-wrap items-center justify-between gap-x-4 gap-y-2 px-4 py-2 sm:px-5">
<p :id="hintId" class="text-sm leading-relaxed text-muted-foreground" aria-live="polite">
{{ status === 'ready' ? labels.hint : status === 'loading' ? labels.loading : labels.unavailable }}
</p>
<button
v-if="status === 'ready'"
type="button"
class="inline-flex min-h-11 cursor-pointer items-center gap-2 rounded-lg border border-border px-3.5 text-sm font-semibold text-foreground transition-colors hover:bg-secondary focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-primary"
@click="toggleGlass"
>
<NuxtIcon name="lucide:layers-2" class="size-4" aria-hidden="true" />
{{ glassVisible ? labels.hideGlass : labels.showGlass }}
</button>
</figcaption>
</figure>
</template>