Color matrix

Edit a feColorMatrix live with sliders, presets and the raw matrix, and compare against the original.

What you are seeing

A bright landscape with a yellow sun, three hills in green, teal and purple, a red balloon and a row of six colour swatches. The right part of the picture is tinted by the colour matrix and the left part is unchanged, split by a white line with a round magenta handle.

How it works

feColorMatrix has three easy modes and one general one. Saturate and hueRotate take a single number. The matrix mode takes 20 numbers: four rows for red, green, blue and alpha, each with a weight for the four input channels and an offset.

Here the three modes are chained in one filter. The sliders drive the first two, and the preset menu and number grid drive the third. Presets such as grayscale, sepia and invert are just different sets of 20 numbers.

The picture is defined once and used twice. The right copy goes through the filter and is clipped at the divider, so the left side stays original for comparison.

Source

/lab/color-matrix/index.html
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width,initial-scale=1">
<title>Color matrix</title>
<meta name="description" content="Edit a feColorMatrix live with sliders, presets and the raw 4 by 5 matrix. Drag the divider to compare.">
<link rel="stylesheet" href="../lab.css">
<style>
.divider{stroke:#fff;stroke-width:3}
.knob{fill:#d4006a;stroke:#fff;stroke-width:3}
.grid{display:grid;grid-template-columns:repeat(5,52px);gap:3px}
.grid input{width:52px;min-height:26px;padding:1px 4px;font-size:12px}
details{flex:1 1 100%}
summary{cursor:pointer;color:var(--muted)}
</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">Color matrix</title>
      <desc id="d">A bright landscape with a sun, three hills, a balloon and six colour swatches. The right side of the picture is passed through a colour matrix filter and the left side is the original. A magenta divider handle moves the split and can be dragged or moved with the arrow keys.</desc>
      <defs>
        <linearGradient id="sky" x1="0" y1="0" x2="0" y2="1"><stop offset="0" stop-color="#58b4f5"/><stop offset="1" stop-color="#ffd9a8"/></linearGradient>
        <filter id="cm" x="0" y="0" width="100%" height="100%" color-interpolation-filters="sRGB">
          <feColorMatrix id="fSat" type="saturate" values="1"/>
          <feColorMatrix id="fHue" type="hueRotate" values="0"/>
          <feColorMatrix id="fMat" type="matrix" values="1 0 0 0 0  0 1 0 0 0  0 0 1 0 0  0 0 0 1 0"/>
        </filter>
        <g id="scene">
          <rect width="400" height="300" fill="url(#sky)"/>
          <circle cx="300" cy="80" r="38" fill="#ffd028"/>
          <path d="M0 230 Q90 120 200 215 T400 200 V300 H0Z" fill="#2fae5f"/>
          <path d="M0 260 Q120 170 260 250 T400 240 V300 H0Z" fill="#157a78"/>
          <path d="M0 285 Q150 220 400 275 V300 H0Z" fill="#6a3fb5"/>
          <ellipse cx="110" cy="105" rx="26" ry="32" fill="#e4352d"/><path d="M110 137 L104 160 H116Z" fill="#8a2a1f"/>
          <g transform="translate(24 20)"><rect width="30" height="14" fill="#e4352d"/><rect x="34" width="30" height="14" fill="#2fae5f"/><rect x="68" width="30" height="14" fill="#1f3fe0"/><rect x="102" width="30" height="14" fill="#ffd028"/><rect x="136" width="30" height="14" fill="#d4006a"/><rect x="170" width="30" height="14" fill="#18b8d8"/></g>
        </g>
        <clipPath id="rightHalf"><rect id="clipRect" x="200" y="0" width="200" height="300"/></clipPath>
      </defs>
      <use href="#scene"/>
      <g clip-path="url(#rightHalf)"><g filter="url(#cm)"><use href="#scene"/></g></g>
      <line id="line" class="divider" x1="200" x2="200" y1="0" y2="300"/>
      <circle id="knob" class="knob grab" cx="200" cy="150" r="12" tabindex="0" role="slider" aria-label="Comparison divider" aria-valuemin="0" aria-valuemax="100" aria-valuenow="50"/>
    </svg>
  </div>
  <div class="bar">
    <label><span>Preset</span><select id="preset"></select></label>
    <label><span>Saturate</span><input id="sat" type="range" min="0" max="3" step="0.05" value="1"></label>
    <label><span>Hue</span><input id="hue" type="range" min="0" max="360" value="0"><output id="hueo">0&deg;</output></label>
    <details><summary>Matrix values (4 rows by 5 columns)</summary><div class="grid" id="grid" role="group" aria-label="Colour matrix values"></div></details>
  </div>
</main>
<script src="../lab.js"></script>
<script src="demo.js"></script>
</body>
</html>
/lab/color-matrix/demo.js
(function () {
  'use strict';
  var $ = Lab.$, svg = $('#svg');
  var presets = {
    'Identity': [1,0,0,0,0, 0,1,0,0,0, 0,0,1,0,0, 0,0,0,1,0],
    'Grayscale': [.2126,.7152,.0722,0,0, .2126,.7152,.0722,0,0, .2126,.7152,.0722,0,0, 0,0,0,1,0],
    'Sepia': [.393,.769,.189,0,0, .349,.686,.168,0,0, .272,.534,.131,0,0, 0,0,0,1,0],
    'Invert': [-1,0,0,0,1, 0,-1,0,0,1, 0,0,-1,0,1, 0,0,0,1,0],
    'Swap red and blue': [0,0,1,0,0, 0,1,0,0,0, 1,0,0,0,0, 0,0,0,1,0],
    'High contrast': [1.6,0,0,0,-.3, 0,1.6,0,0,-.3, 0,0,1.6,0,-.3, 0,0,0,1,0],
    'Cool tint': [.8,0,0,0,0, 0,1,.1,0,0, .1,.1,1.2,0,.05, 0,0,0,1,0],
    'Threshold': [0,0,0,0,0, 0,0,0,0,0, 0,0,0,0,0, 0,0,0,1,0]
  };
  presets.Threshold = [ 2,2,2,0,-2, 2,2,2,0,-2, 2,2,2,0,-2, 0,0,0,1,0 ];
  var sel = $('#preset'), grid = $('#grid'), cells = [];
  Object.keys(presets).forEach(function (n) { var o = document.createElement('option'); o.textContent = n; sel.appendChild(o); });
  var rows = ['R', 'G', 'B', 'A'], cols = ['R', 'G', 'B', 'A', '+'];
  for (var i = 0; i < 20; i++) {
    var c = document.createElement('input'); c.type = 'number'; c.step = '0.05';
    c.setAttribute('aria-label', 'Output ' + rows[Math.floor(i / 5)] + ' from input ' + cols[i % 5]);
    c.addEventListener('input', fromGrid); grid.appendChild(c); cells.push(c);
  }
  function fromGrid() { $('#fMat').setAttribute('values', cells.map(function (c) { return c.value === '' ? 0 : c.value; }).join(' ')); }
  function setMatrix(m) { m.forEach(function (v, i) { cells[i].value = v; }); fromGrid(); }
  sel.addEventListener('change', function () { $('#sat').value = 1; $('#hue').value = 0; $('#hueo').innerHTML = '0&deg;'; $('#fSat').setAttribute('values', 1); $('#fHue').setAttribute('values', 0); setMatrix(presets[sel.value]); });
  $('#sat').addEventListener('input', function (e) { $('#fSat').setAttribute('values', e.target.value); });
  $('#hue').addEventListener('input', function (e) { $('#fHue').setAttribute('values', e.target.value); $('#hueo').innerHTML = e.target.value + '&deg;'; });

  var knob = $('#knob'), x = 200, auto = !Lab.reduced, dir = 1;
  function setX(v) {
    x = Lab.clamp(v, 0, 400);
    knob.setAttribute('cx', x.toFixed(1)); $('#line').setAttribute('x1', x.toFixed(1)); $('#line').setAttribute('x2', x.toFixed(1));
    $('#clipRect').setAttribute('x', x.toFixed(1)); $('#clipRect').setAttribute('width', (400 - x).toFixed(1));
    knob.setAttribute('aria-valuenow', Math.round(x / 4));
  }
  var loop = Lab.loop(function (dt) { var n = x + dir * dt * 40; if (n > 330) dir = -1; if (n < 70) dir = 1; setX(n); });
  function stop() { auto = false; loop.stop(); }
  Lab.drag(knob, { space: svg, down: stop, move: function (p) { setX(p.x); } });
  knob.addEventListener('keydown', function (e) {
    var s = e.shiftKey ? 40 : 8;
    if (e.key === 'ArrowLeft' || e.key === 'ArrowDown') setX(x - s); else if (e.key === 'ArrowRight' || e.key === 'ArrowUp') setX(x + s);
    else if (e.key === 'Home') setX(0); else if (e.key === 'End') setX(400); else return;
    stop(); e.preventDefault();
  });
  [sel, $('#sat'), $('#hue'), grid].forEach(function (el) { el.addEventListener('focusin', stop); el.addEventListener('pointerdown', stop); });
  sel.value = 'Sepia'; setMatrix(presets.Sepia); setX(Lab.reduced ? 200 : 120);
  if (auto) loop.start();
})();
/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}}