全部效果自动播放与循环

光线步进动态雕塑

Raymarched Kinetic Sculpture

浏览器通过距离场计算光线步进,在三维场景里呈现旋转圆环和环绕的小球。

播放动效或调整角度

适用场景

用于首屏点缀或交互式产品灵感页,以程序化数学形状表现三维动感。 适合放在独立的 3D 样片中,用视角控件帮助访客看清几何形状和光照的关系。

应用示例

数字雕塑展给一座抛光圆环和环绕的小球提供可播放的样片。访客暂停后调整观察角度,可以看到边缘光在曲面上的位置随之改变。

AI 提示词

为【目标区域】制作光线步进动态雕塑。对圆环与移动小球的距离场执行球体追踪,用差分估算法线,并区分主光与边缘光。只在用户播放且预览可见时持续渲染。提供可用键盘或触屏操作的参数控件,限制渲染分辨率,并在 WebGL 不可用时提供可读的降级状态。

示例代码

保存为 HTML 文件后,用浏览器打开即可运行。代码与页面里的演示一致。

查看 HTML
<!doctype html>
<html lang="zh">
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>光线步进动态雕塑</title>
  <style>
    :root {
      color-scheme: dark;
      --demo-bg: #171629;
      --demo-ink: #f8f5ff;
      --demo-accent: #b9a6ff;
      --demo-muted: #bfbbd3;
      font-family: system-ui, sans-serif;
      color: var(--demo-ink);
      background: var(--demo-bg);
    }

    *, *::before, *::after { box-sizing: border-box; }
    body { margin: 0; min-width: 0; }
    button, input { font: inherit; }

    .demo {
      display: grid;
      place-items: center;
      align-content: center;
      min-height: 100vh;
      padding: 14px;
      overflow: hidden;
      background: radial-gradient(ellipse at 50% 24%, #28233f, var(--demo-bg) 78%);
    }

    .demo-button {
      border: 1px solid #ffffff3d;
      border-radius: 7px;
      background: #ffffff12;
      color: var(--demo-ink);
      padding: 6px 11px;
      font-size: 12px;
      cursor: pointer;
    }

    :focus-visible {
      outline: 2px solid var(--demo-accent);
      outline-offset: 3px;
    }

    .shader-demo { width: min(100%, 465px); display: grid; grid-template-columns: minmax(0, 1fr); gap: 8px; }
    .shader-stage {
      display: grid; overflow: hidden; border: 1px solid #d8cef144; border-radius: 11px;
      min-height: clamp(88px, 58vh, 260px); background: radial-gradient(ellipse at center, #4b3767 16%, #a16e55 30%, #201936 56%, #100f24);
    }
    .shader-stage canvas { display: block; width: 100%; height: clamp(88px, 58vh, 260px); }
    .shader-controls { display: flex; align-items: center; gap: 10px; min-height: 32px; color: var(--demo-ink); }
    .shader-controls label { display: flex; align-items: center; gap: 8px; min-width: 0; flex: 1; font-size: 12px; }
    .shader-controls span { white-space: nowrap; }
    .shader-controls input { flex: 1; min-width: 0; margin: 0; accent-color: #d1b5ff; }
    .shader-fallback { display: none; align-self: center; justify-self: center; margin: 6px; padding: 6px 10px; border-radius: 5px; background: #161327; color: #fff; font-size: 12px; text-align: center; }
    .shader-demo[data-mode="fallback"] :is(canvas, .shader-controls) { display: none; }
    .shader-demo[data-mode="fallback"] .shader-fallback { display: block; }
    @media (prefers-reduced-motion: reduce) { [data-shader-toggle] { display: none; } }
  </style>
</head>
<body>
  <main class="demo">
    <div class="shader-demo">
      <div class="shader-stage">
        <canvas role="img" aria-label="光线步进动态雕塑"></canvas>
        <p class="shader-fallback" role="status">WebGL 不可用。当前显示静态配色。</p>
      </div>
      <div class="shader-controls">
        <label><span>观察角度</span><input type="range" min="0" max="100" value="44"></label>
        <button type="button" class="demo-button" data-shader-toggle aria-pressed="false">播放</button>
      </div>
    </div>
  </main>
  <script>
    const fragmentSource = "precision highp float;\n\nuniform vec2 resolution;\nuniform float amount;\nuniform float elapsed;\n\nvec2 hash2(vec2 position) {\n  vec2 noise = vec2(dot(position, vec2(93.17, 173.41)), dot(position, vec2(187.39, 61.77)));\n  return fract(sin(noise) * 16453.9341);\n}\n\nmat2 turn(float angle) {\n  float s = sin(angle);\n  float c = cos(angle);\n  return mat2(c, s, -s, c);\n}\n\nfloat sculpture(vec3 point) {\n  point.xz = turn(amount * 2.6 + elapsed * 0.78) * point.xz;\n  point.yz = turn(0.6 + elapsed * 0.44) * point.yz;\n  float ring = length(vec2(length(point.xz) - 0.58, point.y)) - 0.185;\n  vec3 orbit = vec3(0.58 * cos(elapsed), 0.46, 0.58 * sin(elapsed));\n  float bead = length(point - orbit) - 0.18;\n  return min(ring, bead);\n}\nvec3 paint(vec2 p, vec2 uv) {\n  vec3 eye = vec3(0.0, 0.0, 3.2);\n  vec3 ray = normalize(vec3(p, -2.87));\n  float traveled = 0.0;\n  bool hit = false;\n  for (int stepCount = 0; stepCount < 48; stepCount++) {\n    float gap = sculpture(eye + traveled * ray);\n    if (gap < 0.002) { hit = true; break; }\n    traveled += gap;\n    if (traveled > 6.0) break;\n  }\n  vec3 fog = mix(vec3(0.06, 0.055, 0.16), vec3(0.26, 0.16, 0.36), exp(-dot(p, p) * 0.8));\n  if (!hit) return fog;\n  vec3 point = eye + traveled * ray;\n  float e = 0.007;\n  vec3 normal = normalize(vec3(\n    sculpture(point + vec3(e, 0.0, 0.0)) - sculpture(point - vec3(e, 0.0, 0.0)),\n    sculpture(point + vec3(0.0, e, 0.0)) - sculpture(point - vec3(0.0, e, 0.0)),\n    sculpture(point + vec3(0.0, 0.0, e)) - sculpture(point - vec3(0.0, 0.0, e))\n  ));\n  float key = max(0.0, dot(normal, normalize(vec3(-0.7, 0.66, 0.8))));\n  float fill = max(0.0, dot(normal, normalize(vec3(0.8, 0.35, -0.5))));\n  float edge = pow(1.0 - max(0.0, dot(normal, -ray)), 2.5);\n  return vec3(0.12, 0.13, 0.28) + key * vec3(0.93, 0.50, 0.22)\n    + fill * vec3(0.19, 0.41, 0.54) + edge * vec3(0.12, 0.17, 0.32);\n}\n\nvoid main() {\n  vec2 uv = gl_FragCoord.xy / resolution;\n  vec2 centered = (2.0 * gl_FragCoord.xy - resolution) / resolution.y;\n  gl_FragColor = vec4(clamp(paint(centered, uv), 0.0, 1.0), 1.0);\n}";
    const playLabel = "播放";
    const pauseLabel = "暂停";

    const scene = document.querySelector('.shader-demo');
    const display = scene.querySelector('canvas');
    const output = display.getContext('2d', { alpha: false });
    const control = scene.querySelector('input');
    const toggle = scene.querySelector('[data-shader-toggle]');
    const motion = matchMedia('(prefers-reduced-motion: reduce)');
    let surface = null;
    let visible = true;
    let playing = false;
    let frame = 0;
    let lastTime = 0;
    let time = 0;
    let idle = 0;

    function compile(gl, kind, source) {
      const shader = gl.createShader(kind);
      gl.shaderSource(shader, source);
      gl.compileShader(shader);
      if (gl.getShaderParameter(shader, gl.COMPILE_STATUS)) return shader;
      console.warn(gl.getShaderInfoLog(shader));
      gl.deleteShader(shader);
      return null;
    }

    function createSurface() {
      const canvas = document.createElement('canvas');
      const gl = canvas.getContext('webgl', { alpha: false, antialias: false });
      if (!gl) return null;

      const vertex = compile(gl, gl.VERTEX_SHADER,
        'attribute vec2 point; void main() { gl_Position = vec4(point, 0.0, 1.0); }');
      const fragment = compile(gl, gl.FRAGMENT_SHADER, fragmentSource);
      const program = gl.createProgram();
      if (vertex && fragment) {
        gl.attachShader(program, vertex);
        gl.attachShader(program, fragment);
        gl.linkProgram(program);
      }
      if (vertex) gl.deleteShader(vertex);
      if (fragment) gl.deleteShader(fragment);
      if (!gl.getProgramParameter(program, gl.LINK_STATUS)) {
        gl.deleteProgram(program);
        gl.getExtension('WEBGL_lose_context')?.loseContext();
        return null;
      }

      gl.useProgram(program);
      const vertices = gl.createBuffer();
      gl.bindBuffer(gl.ARRAY_BUFFER, vertices);
      gl.bufferData(gl.ARRAY_BUFFER, new Float32Array([-1, -1, 3, -1, -1, 3]), gl.STATIC_DRAW);
      const point = gl.getAttribLocation(program, 'point');
      gl.enableVertexAttribArray(point);
      gl.vertexAttribPointer(point, 2, gl.FLOAT, false, 0, 0);

      return {
        canvas,
        gl,
        program,
        vertices,
        resolution: gl.getUniformLocation(program, 'resolution'),
        amount: gl.getUniformLocation(program, 'amount'),
        elapsed: gl.getUniformLocation(program, 'elapsed')
      };
    }

    function release() {
      clearTimeout(idle);
      if (!surface) return;
      const { gl, program, vertices } = surface;
      gl.deleteBuffer(vertices);
      gl.deleteProgram(program);
      gl.getExtension('WEBGL_lose_context')?.loseContext();
      surface = null;
    }

    function paint() {
      const size = display.getBoundingClientRect();
      if (!size.width || !size.height) return;
      if (surface?.gl.isContextLost()) release();
      surface ??= createSurface();
      if (!output || !surface) {
        scene.dataset.mode = 'fallback';
        suspend();
        return;
      }

      const pixelRatio = Math.min(window.devicePixelRatio || 1, 1.35);
      const width = Math.max(1, Math.min(Math.round(size.width * pixelRatio), 540));
      const height = Math.max(1, Math.round(size.height * width / size.width));
      const { canvas, gl } = surface;
      if (canvas.width !== width || canvas.height !== height) {
        canvas.width = width;
        canvas.height = height;
      }
      if (display.width !== width || display.height !== height) {
        display.width = width;
        display.height = height;
      }
      gl.viewport(0, 0, width, height);
      gl.uniform2f(surface.resolution, width, height);
      gl.uniform1f(surface.amount, Number(control.value) / 100);
      gl.uniform1f(surface.elapsed, time);
      gl.drawArrays(gl.TRIANGLES, 0, 3);
      output.drawImage(canvas, 0, 0);
      scene.dataset.mode = 'rendered';
    }

    function tick(now) {
      frame = 0;
      if (playing && lastTime) time += Math.min(60, now - lastTime) / 1000;
      lastTime = now;
      paint();
      if (playing) requestRender();
      else idle = setTimeout(release, 950);
    }

    function requestRender() {
      if (frame || !visible || document.hidden || scene.dataset.mode === 'fallback') return;
      clearTimeout(idle);
      frame = requestAnimationFrame(tick);
    }

    function suspend() {
      cancelAnimationFrame(frame);
      frame = 0;
      lastTime = 0;
      release();
    }

    function setPlaying(next) {
      playing = next && !motion.matches;
      lastTime = 0;
      if (toggle) {
        toggle.textContent = playing ? pauseLabel : playLabel;
        toggle.setAttribute('aria-pressed', String(playing));
      }
      requestRender();
    }

    control.addEventListener('input', requestRender);
    toggle?.addEventListener('click', () => setPlaying(!playing));
    motion.addEventListener('change', () => { if (motion.matches) setPlaying(false); });
    new ResizeObserver(requestRender).observe(display);
    new IntersectionObserver(([entry]) => {
      visible = entry.isIntersecting;
      if (visible) requestRender();
      else suspend();
    }).observe(display);
    document.addEventListener('visibilitychange', () => {
      if (document.hidden) suspend();
      else requestRender();
    });
    window.addEventListener('pagehide', suspend);
    window.addEventListener('pageshow', requestRender);
    requestRender();
  </script>
</body>
</html>

UI Skills 原创示例

相关参考