Light lab

Light a procedural bump map with diffuse and specular lighting, and drag the lamp around.

What you are seeing

A blue bumpy textured surface with a lighter circle and a darker rounded square is lit from a magenta lamp handle with short rays. Bright highlights and soft shadows sit on the bumps and shift as the lamp moves.

How it works

feTurbulence makes noise, and a colour matrix copies its brightness into the alpha channel. Lighting filters read that alpha channel as a height map, so noise becomes bumpy terrain.

feDiffuseLighting shades the surface by the angle between each bump and the light. It is multiplied with the source graphic to tint it. feSpecularLighting adds shiny highlights, and a final feComposite adds them on top.

The light is an fePointLight or feSpotLight with x, y and z values. The magenta lamp is a normal draggable circle, and its position is written into both lights as you move it.

Source

/lab/light-lab/index.html
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width,initial-scale=1">
<title>Light lab</title>
<meta name="description" content="Light a noise bump map with feDiffuseLighting and feSpecularLighting. Drag the lamp.">
<link rel="stylesheet" href="../lab.css">
<style>
.lamp{fill:#d4006a;stroke:#fff;stroke-width:3}
.ray{stroke:#d4006a;stroke-width:2.5;stroke-linecap:round;pointer-events:none}
</style>
</head>
<body>
<main class="demo">
  <div class="stage">
    <svg id="svg" class="drag-surface" viewBox="0 0 400 300" role="group" aria-labelledby="t d">
      <title id="t">Light lab</title>
      <desc id="d">A blue textured surface made from procedural noise is lit by a light. A magenta lamp handle shows where the light sits and can be dragged or moved with the arrow keys. Highlights and shadows on the bumps follow the lamp.</desc>
      <defs>
        <filter id="lit" filterUnits="userSpaceOnUse" x="0" y="0" width="400" height="300" color-interpolation-filters="sRGB">
          <feTurbulence type="fractalNoise" baseFrequency="0.012" numOctaves="3" seed="7" result="noise"/>
          <feColorMatrix in="noise" type="matrix" values="0 0 0 0 0  0 0 0 0 0  0 0 0 0 0  0.33 0.33 0.33 0 0" result="bump"/>
          <feDiffuseLighting id="diff" in="bump" surfaceScale="5" diffuseConstant="1" lighting-color="#ffffff" result="d"><fePointLight id="l1" x="200" y="120" z="80"/></feDiffuseLighting>
          <feComposite in="d" in2="SourceGraphic" operator="arithmetic" k1="1" k2="0" k3="0" k4="0" result="lit"/>
          <feSpecularLighting id="spec" in="bump" surfaceScale="5" specularConstant="0.8" specularExponent="24" lighting-color="#ffffff" result="s"><fePointLight id="l2" x="200" y="120" z="80"/></feSpecularLighting>
          <feComposite in="s" in2="lit" operator="arithmetic" k1="0" k2="1" k3="1" k4="0"/>
        </filter>
      </defs>
      <g filter="url(#lit)">
        <rect width="400" height="300" fill="#8296f2"/>
        <circle cx="110" cy="190" r="62" fill="#c3cdfa"/>
        <rect x="230" y="60" width="120" height="120" rx="18" fill="#4a63e6"/>
      </g>
      <g id="lampG">
        <g id="rays"></g>
        <circle id="lamp" class="lamp grab" r="11" tabindex="0" role="button" aria-label="Light position" aria-describedby="hint"/>
      </g>
    </svg>
  </div>
  <div class="bar">
    <button id="orbit" type="button">Pause</button>
    <label><span>Light</span><select id="type"><option value="point">Point</option><option value="spot">Spot</option></select></label>
    <label><span>Colour</span><select id="col"><option value="#ffffff">White</option><option value="#ffd9a0">Warm</option><option value="#a8c4ff">Cool</option></select></label>
    <label><span>Height</span><input id="z" type="range" min="15" max="220" value="80"></label>
    <label><span>Bumps</span><input id="ss" type="range" min="0" max="20" value="5"></label>
    <label><span>Shine</span><input id="shine" type="range" min="2" max="80" value="24"></label>
  </div>
  <p class="sr-only" id="hint">Arrow keys move the light by 8, shift plus arrow by 32.</p>
</main>
<script src="../lab.js"></script>
<script src="demo.js"></script>
</body>
</html>
/lab/light-lab/demo.js
(function () {
  'use strict';
  var $ = Lab.$, svg = $('#svg'), lamp = $('#lamp'), diff = $('#diff'), spec = $('#spec');
  var L = { x: 200, y: 120, z: 80 }, orbiting = false, t = 0;
  for (var i = 0; i < 8; i++) { var a = i * Math.PI / 4; Lab.make('line', { class: 'ray', x1: Math.cos(a) * 16, y1: Math.sin(a) * 16, x2: Math.cos(a) * 22, y2: Math.sin(a) * 22 }, $('#rays')); }
  function lights() { return [$('#l1'), $('#l2')]; }
  function apply() {
    L.x = Lab.clamp(L.x, 0, 400); L.y = Lab.clamp(L.y, 0, 300);
    lights().forEach(function (l) {
      l.setAttribute('x', L.x.toFixed(1)); l.setAttribute('y', L.y.toFixed(1)); l.setAttribute('z', L.z);
    });
    $('#lampG').setAttribute('transform', 'translate(' + L.x.toFixed(1) + ' ' + L.y.toFixed(1) + ')');
    lamp.setAttribute('aria-label', 'Light position, x ' + Math.round(L.x) + ', y ' + Math.round(L.y));
  }
  function setType(type) {
    [[diff, 'l1'], [spec, 'l2']].forEach(function (p) {
      var old = $('#' + p[1]), n = document.createElementNS(Lab.NS, type === 'spot' ? 'feSpotLight' : 'fePointLight');
      n.id = p[1];
      if (type === 'spot') { n.setAttribute('pointsAtX', 200); n.setAttribute('pointsAtY', 150); n.setAttribute('pointsAtZ', 0); n.setAttribute('limitingConeAngle', 38); n.setAttribute('specularExponent', 4); }
      p[0].replaceChild(n, old);
    });
    apply();
  }
  function stopOrbit() { setOrbit(false); }
  function setOrbit(on) { orbiting = on; $('#orbit').textContent = on ? 'Pause' : 'Orbit'; if (on) loop.start(); else loop.stop(); }
  var loop = Lab.loop(function (dt) { t += dt * 0.5; L.x = 200 + Math.cos(t) * 150; L.y = 150 + Math.sin(t * 1.3) * 100; apply(); });
  Lab.drag(lamp, { space: svg, down: stopOrbit, move: function (p) { L.x = p.x; L.y = p.y; apply(); } });
  lamp.addEventListener('keydown', function (e) {
    var s = e.shiftKey ? 32 : 8, d = { ArrowLeft: [-s, 0], ArrowRight: [s, 0], ArrowUp: [0, -s], ArrowDown: [0, s] }[e.key];
    if (!d) return; stopOrbit(); L.x += d[0]; L.y += d[1]; apply(); e.preventDefault();
  });
  $('#orbit').addEventListener('click', function () { setOrbit(!orbiting); });
  $('#type').addEventListener('change', function (e) { setType(e.target.value); });
  $('#col').addEventListener('change', function (e) { diff.setAttribute('lighting-color', e.target.value); spec.setAttribute('lighting-color', e.target.value); });
  $('#z').addEventListener('input', function (e) { L.z = +e.target.value; apply(); });
  $('#ss').addEventListener('input', function (e) { diff.setAttribute('surfaceScale', e.target.value); spec.setAttribute('surfaceScale', e.target.value); });
  $('#shine').addEventListener('input', function (e) { spec.setAttribute('specularExponent', e.target.value); });
  apply();
  if (Lab.reduced) { L.x = 120; L.y = 90; apply(); setOrbit(false); } else setOrbit(true);
})();
/lab/lab.js
/* Small shared helpers for the SVG Wow! lab demos. No dependencies. */
(function () {
  'use strict';
  var NS = 'http://www.w3.org/2000/svg';
  var mq = window.matchMedia('(prefers-reduced-motion: reduce)');
  var Lab = (window.Lab = { NS: NS });
  Object.defineProperty(Lab, 'reduced', { get: function () { return mq.matches; } });
  Lab.$ = function (s, r) { return (r || document).querySelector(s); };
  Lab.$$ = function (s, r) { return Array.prototype.slice.call((r || document).querySelectorAll(s)); };
  Lab.clamp = function (v, a, b) { return Math.max(a, Math.min(b, v)); };
  Lab.lerp = function (a, b, t) { return a + (b - a) * t; };
  Lab.ease = function (t) { return t < 0.5 ? 4 * t * t * t : 1 - Math.pow(-2 * t + 2, 3) / 2; };
  Lab.make = function (tag, attrs, parent) {
    var e = document.createElementNS(NS, tag);
    if (attrs) for (var k in attrs) e.setAttribute(k, attrs[k]);
    if (parent) parent.appendChild(e);
    return e;
  };
  /* Client point to the user space of `el` (any SVG graphics element). */
  Lab.pt = function (el, evt) {
    var m = el.getScreenCTM();
    if (!m) return { x: 0, y: 0 };
    var p = new DOMPoint(evt.clientX, evt.clientY).matrixTransform(m.inverse());
    return { x: p.x, y: p.y };
  };
  /* requestAnimationFrame loop that pauses while the document is hidden. */
  Lab.loop = function (fn) {
    var raf = 0, last = 0, running = false, wanted = false, self = {};
    function tick(t) {
      if (!running) return;
      raf = requestAnimationFrame(tick);
      var dt = last ? Math.min((t - last) / 1000, 0.1) : 0;
      last = t;
      fn(dt, t / 1000);
    }
    function go() { if (running || document.hidden || !wanted) return; running = true; last = 0; raf = requestAnimationFrame(tick); }
    function halt() { running = false; cancelAnimationFrame(raf); }
    self.start = function () { wanted = true; go(); };
    self.stop = function () { wanted = false; halt(); };
    self.running = function () { return wanted; };
    document.addEventListener('visibilitychange', function () { if (document.hidden) halt(); else go(); });
    return self;
  };
  /* Pointer drag with capture. space: element whose user space the points use. */
  Lab.drag = function (el, o) {
    var active = false, space = o.space || el.ownerSVGElement || el;
    el.addEventListener('pointerdown', function (e) {
      if (e.button > 0) return;
      active = true;
      try { el.setPointerCapture(e.pointerId); } catch (_) {}
      if (o.down) o.down(Lab.pt(space, e), e);
      e.preventDefault();
    });
    el.addEventListener('pointermove', function (e) { if (active) o.move(Lab.pt(space, e), e); });
    function end(e) {
      if (!active) return;
      active = false;
      try { el.releasePointerCapture(e.pointerId); } catch (_) {}
      if (o.up) o.up(e);
    }
    el.addEventListener('pointerup', end);
    el.addEventListener('pointercancel', end);
  };
  Lab.say = function (msg) {
    var l = document.getElementById('live');
    if (l) l.textContent = msg;
  };
})();
/lab/lab.css
:root{--bg:#f1f2f4;--ink:#24272c;--blue:#1f3fe0;--mag:#d4006a;--line:#c9ccd3;--panel:#fff;--muted:#555b66;font-family:system-ui,-apple-system,"Segoe UI",Roboto,Helvetica,Arial,sans-serif}
*{box-sizing:border-box}
html,body{margin:0;height:100%;background:var(--bg);color:var(--ink);overflow-x:hidden}
body{font-size:13px;line-height:1.3}
.demo{display:flex;flex-direction:column;height:100%;min-height:0}
.stage{flex:1 1 auto;min-height:120px;position:relative;overflow:hidden;background:var(--bg)}
.stage>svg{position:absolute;left:0;top:0;width:100%;height:100%;display:block}
.bar{flex:0 0 auto;display:flex;flex-wrap:wrap;gap:6px 14px;align-items:center;padding:6px 10px;background:var(--panel);border-top:1px solid var(--line);max-height:46%;overflow:auto}
.bar .grp{display:flex;flex-wrap:wrap;align-items:center;gap:6px 10px}
label{display:inline-flex;align-items:center;gap:6px;white-space:nowrap}
label>span,.dim{color:var(--muted)}
output{font-variant-numeric:tabular-nums;min-width:3.2ch;display:inline-block}
button,select,input[type=number],input[type=text]{font:inherit;color:var(--ink);background:#fff;border:1px solid #8a909b;border-radius:6px;padding:3px 8px;min-height:28px}
button{border-color:var(--ink);cursor:pointer}
button:hover{background:#e7e9ef}
button[aria-pressed=true]{background:var(--ink);color:#fff}
input[type=range]{width:110px;accent-color:var(--blue);margin:0}
input[type=color]{width:34px;height:28px;padding:1px;border:1px solid #8a909b;border-radius:6px;background:#fff}
input[type=checkbox]{accent-color:var(--blue);width:16px;height:16px}
:focus-visible{outline:3px solid var(--blue);outline-offset:2px}
.grab{cursor:grab;touch-action:none}
.grab:active{cursor:grabbing}
.grab:focus-visible{outline:none;stroke:var(--blue);stroke-width:4px}
.drag-surface{touch-action:none}
.ro{font-size:11px;color:var(--muted)}
.sr-only{position:absolute;width:1px;height:1px;overflow:hidden;clip:rect(0 0 0 0);white-space:nowrap}
svg text{font-family:inherit}
pre,textarea{font:11px/1.35 ui-monospace,SFMono-Regular,Menlo,Consolas,monospace}
@media (pointer:coarse){button,select,input[type=number]{min-height:38px}input[type=range]{height:30px}}
@media (max-width:420px){.bar{gap:6px 10px;padding:6px 8px}input[type=range]{width:96px}}
@media (min-width:700px){.demo.split{flex-direction:row}.demo.split .stage{flex:1 1 auto}.demo.split .bar{width:320px;max-height:none;flex:0 0 320px;border-top:0;border-left:1px solid var(--line);align-content:flex-start}}