Tangram

Drag, rotate and snap seven tangram pieces into a square, using mouse, touch or keyboard.

What you are seeing

Seven coloured flat pieces are scattered on the left: two large triangles, a medium triangle, two small triangles, a square and a parallelogram. A pale grey square outline on the right is the target. Loose pieces have magenta outlines, and placed pieces have white outlines. A counter shows how many are placed.

How it works

Each piece is a polygon drawn around its own centre and placed with a translate, rotate and scale transform. Dragging changes the translation, and rotation moves in 45 degree steps.

Snapping compares the vertices of the dropped piece with those of each free target outline of the same kind. If every vertex lies within a small distance of a target vertex, the piece jumps to that target. Comparing vertices instead of angles handles the symmetry of the square and triangles for free.

Everything has a keyboard path. Tab to a piece, move it with the arrow keys, rotate with R, flip with F and press Enter to drop it into place.

Source

/lab/tangram/index.html
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width,initial-scale=1">
<title>Tangram</title>
<meta name="description" content="Drag, rotate and snap seven tangram pieces into a square, with mouse, touch or keyboard.">
<link rel="stylesheet" href="../lab.css">
<style>
.slot{fill:#e3e5ea;stroke:#c3c7cf;stroke-width:1}
.hint{fill:none;stroke:#1f3fe0;stroke-width:1.5;stroke-dasharray:4 3}
.piece{stroke:#d4006a;stroke-width:2.5;stroke-linejoin:round}
.piece.placed{stroke:#fff;stroke-width:1.5}
.piece.sel{stroke-width:4}
.piece.placed.sel{stroke:#d4006a}
.msg{font-size:15px;font-weight:700;fill:#1f3fe0}
</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">Tangram</title>
      <desc id="d">Seven flat pieces, two large triangles, one medium triangle, two small triangles, a square and a parallelogram, are scattered on the left. A grey square outline on the right is the target. Each piece has a magenta outline until it clicks into place in the square.</desc>
      <g id="slots"></g>
      <g id="hints"></g>
      <g id="pieces"></g>
      <text id="msg" class="msg" x="312" y="248" text-anchor="middle"></text>
    </svg>
  </div>
  <div class="bar">
    <button id="rot" type="button">Rotate</button>
    <button id="flip" type="button">Flip</button>
    <button id="hint" type="button" aria-pressed="false">Hint</button>
    <button id="shuffle" type="button">Shuffle</button>
    <button id="reset" type="button">Reset</button>
    <output id="count">0 of 7 placed</output>
  </div>
  <p class="sr-only" id="help">Arrow keys move the piece, shift plus arrow moves further. R rotates, shift R rotates back, F flips, Enter or Space drops the piece into place if it is close.</p>
  <p class="sr-only" id="live" aria-live="polite"></p>
</main>
<script src="../lab.js"></script>
<script src="demo.js"></script>
</body>
</html>
/lab/tangram/demo.js
(function () {
  'use strict';
  var $ = Lab.$, svg = $('#svg'), U = 34, OX = 244, OY = 82, TOL = 15;
  // Classic tangram cut of a 4 by 4 square. Coordinates are in grid units.
  var defs = [
    { name: 'Large triangle A', v: [[0, 0], [4, 0], [2, 2]], fill: '#1f3fe0' },
    { name: 'Large triangle B', v: [[4, 0], [4, 4], [2, 2]], fill: '#4560e8' },
    { name: 'Medium triangle', v: [[0, 2], [0, 4], [2, 4]], fill: '#24272c' },
    { name: 'Small triangle A', v: [[0, 0], [1, 1], [0, 2]], fill: '#565e6c' },
    { name: 'Square', v: [[1, 1], [2, 2], [1, 3], [0, 2]], fill: '#8ea0f2' },
    { name: 'Small triangle B', v: [[2, 2], [3, 3], [1, 3]], fill: '#7c8493' },
    { name: 'Parallelogram', v: [[1, 3], [2, 4], [4, 4], [3, 3]], fill: '#2d4ad2' }
  ];
  var start = [[70, 70, 45], [150, 80, 135], [70, 170, 0], [150, 160, 90], [215, 215, 0], [60, 250, 180], [140, 245, 45]];
  function kind(n) { return n.replace(/ [AB]$/, ''); }
  function world(local, s) {
    var a = s.rot * Math.PI / 180, c = Math.cos(a), n = Math.sin(a);
    return local.map(function (p) { var x = p[0] * (s.flip ? -1 : 1); return [s.x + x * c - p[1] * n, s.y + x * n + p[1] * c]; });
  }
  function near(A, B) {
    return A.every(function (p) { return B.some(function (q) { return Math.hypot(p[0] - q[0], p[1] - q[1]) < TOL; }); });
  }
  function pts(w) { return w.map(function (p) { return p[0].toFixed(1) + ',' + p[1].toFixed(1); }).join(' '); }
  var sel = null, slotTaken = [];
  var pieces = defs.map(function (d, i) {
    var cx = d.v.reduce(function (s, p) { return s + p[0]; }, 0) / d.v.length, cy = d.v.reduce(function (s, p) { return s + p[1]; }, 0) / d.v.length;
    d.local = d.v.map(function (p) { return [(p[0] - cx) * U, (p[1] - cy) * U]; });
    var home = { x: OX + cx * U, y: OY + cy * U, rot: 0, flip: false };
    Lab.make('polygon', { class: 'slot', points: pts(world(d.local, home)) }, $('#slots'));
    Lab.make('polygon', { class: 'hint', points: pts(world(d.local, home)) }, $('#hints'));
    var el = Lab.make('polygon', { class: 'piece grab', fill: d.fill, points: pts(d.local.map(function (p) { return [p[0], p[1]]; })), tabindex: 0, role: 'button', 'aria-describedby': 'help' }, $('#pieces'));
    var pc = { def: d, el: el, home: home, s: { x: start[i][0], y: start[i][1], rot: start[i][2], flip: false }, slot: -1 };
    el.addEventListener('focus', function () { select(pc); });
    wire(pc);
    return pc;
  });
  $('#hints').style.display = 'none';
  function draw(pc) {
    pc.el.setAttribute('transform', 'translate(' + pc.s.x.toFixed(1) + ' ' + pc.s.y.toFixed(1) + ') rotate(' + pc.s.rot + ') scale(' + (pc.s.flip ? -1 : 1) + ' 1)');
    pc.el.setAttribute('aria-label', pc.def.name + ', ' + (pc.slot >= 0 ? 'placed' : 'not placed') + ', rotated ' + ((pc.s.rot % 360 + 360) % 360) + ' degrees' + (pc.s.flip ? ', flipped' : ''));
    pc.el.classList.toggle('placed', pc.slot >= 0);
    pc.el.classList.toggle('sel', pc === sel);
  }
  function select(pc) { sel = pc; pieces.forEach(draw); }
  function count() {
    var n = pieces.filter(function (p) { return p.slot >= 0; }).length;
    $('#count').textContent = n + ' of 7 placed';
    $('#msg').textContent = n === 7 ? 'Solved' : '';
    return n;
  }
  function unplace(pc) { if (pc.slot >= 0) { slotTaken[pc.slot] = null; pc.slot = -1; } }
  function trySnap(pc) {
    unplace(pc);
    var w = world(pc.def.local, pc.s);
    for (var i = 0; i < pieces.length; i++) {
      if (slotTaken[i]) continue;
      var d2 = pieces[i].def;
      if (kind(d2.name) !== kind(pc.def.name)) continue;
      var sw = world(d2.local, pieces[i].home);
      if (near(w, sw) && near(sw, w)) {
        pc.s = { x: pieces[i].home.x, y: pieces[i].home.y, rot: 0, flip: false }; pc.slot = i; slotTaken[i] = pc;
        draw(pc); var n = count(); Lab.say(pc.def.name + ' placed. ' + n + ' of 7.' + (n === 7 ? ' Puzzle solved.' : '')); return true;
      }
    }
    draw(pc); count(); return false;
  }
  function wire(pc) {
    var off, moved = 0, lastTap = 0, p0;
    Lab.drag(pc.el, {
      space: svg,
      down: function (p) { select(pc); $('#pieces').appendChild(pc.el); unplace(pc); count(); off = [pc.s.x - p.x, pc.s.y - p.y]; moved = 0; p0 = p; draw(pc); },
      move: function (p) { moved = Math.max(moved, Math.hypot(p.x - p0.x, p.y - p0.y)); pc.s.x = Lab.clamp(p.x + off[0], 12, 388); pc.s.y = Lab.clamp(p.y + off[1], 12, 288); draw(pc); },
      up: function () {
        if (moved < 4) { var now = Date.now(); if (now - lastTap < 400) pc.s.rot += 45; lastTap = now; }
        trySnap(pc);
      }
    });
    pc.el.addEventListener('keydown', function (e) {
      var s = e.shiftKey ? 24 : 6, k = e.key, d = { ArrowLeft: [-s, 0], ArrowRight: [s, 0], ArrowUp: [0, -s], ArrowDown: [0, s] }[k];
      if (d) { unplace(pc); count(); pc.s.x = Lab.clamp(pc.s.x + d[0], 12, 388); pc.s.y = Lab.clamp(pc.s.y + d[1], 12, 288); draw(pc); }
      else if (k === 'r' || k === 'R') { pc.s.rot += e.shiftKey ? -45 : 45; unplace(pc); count(); draw(pc); }
      else if (k === 'f' || k === 'F') { pc.s.flip = !pc.s.flip; unplace(pc); count(); draw(pc); }
      else if (k === 'Enter' || k === ' ') { if (!trySnap(pc)) Lab.say(pc.def.name + ' is not close enough to a matching spot.'); }
      else return;
      e.preventDefault();
    });
  }
  function target() { return sel || pieces.filter(function (p) { return p.slot < 0; })[0] || pieces[0]; }
  $('#rot').addEventListener('click', function () { var p = target(); unplace(p); p.s.rot += 45; select(p); trySnap(p); });
  $('#flip').addEventListener('click', function () { var p = target(); unplace(p); p.s.flip = !p.s.flip; select(p); trySnap(p); });
  $('#hint').addEventListener('click', function (e) { var on = e.currentTarget.getAttribute('aria-pressed') !== 'true'; e.currentTarget.setAttribute('aria-pressed', on); $('#hints').style.display = on ? '' : 'none'; });
  function layout(random) {
    slotTaken = [];
    pieces.forEach(function (pc, i) {
      pc.slot = -1;
      pc.s = random ? { x: 40 + Math.random() * 160, y: 45 + Math.random() * 210, rot: 45 * Math.floor(Math.random() * 8), flip: i === 6 && Math.random() < 0.5 } : { x: start[i][0], y: start[i][1], rot: start[i][2], flip: false };
      draw(pc);
    });
    count();
  }
  $('#shuffle').addEventListener('click', function () { layout(true); });
  $('#reset').addEventListener('click', function () { layout(false); });
  layout(false);
})();
/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}}