Shape morph
Smoothly morph a circle into a star, square, triangle, heart or blob by animating the numbers in one path.
What you are seeing
A blue outlined shape on a light grey ground changes between a circle, four-point star, square, triangle, heart and blob. Dashed grey outlines show the shape it started from and the one it is heading to, and eight small white dots mark the anchor points as they travel. A caption names the two shapes.
How it works
A path morph works when two shapes use exactly the same commands in the same order. Every shape here is written as one move command followed by eight cubic curve commands, so each shape has the same 50 numbers.
Corners are made by giving a curve zero-length handles, and round shapes get handles that follow the neighbouring points. That keeps the structure identical while the look changes.
To animate, the script blends each number from the first shape toward the matching number in the second, then rebuilds the d attribute. The dashed outlines show the two end shapes and the dots follow the eight anchor points.
Source
/lab/shape-morph/index.html
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width,initial-scale=1">
<title>Shape morph</title>
<meta name="description" content="Morph between SVG shapes whose paths share the same cubic commands.">
<link rel="stylesheet" href="../lab.css">
<style>
.ghost{fill:none;stroke:#8a909b;stroke-width:1.5;stroke-dasharray:4 4}
#shape{fill:#1f3fe0;fill-opacity:.88;stroke:#24272c;stroke-width:2.5;stroke-linejoin:round}
.anchor{fill:#fff;stroke:#24272c;stroke-width:1.5}
.cap{font-size:12px;fill:#555b66}
</style>
</head>
<body>
<main class="demo">
<div class="stage">
<svg viewBox="0 0 400 300" role="img" aria-labelledby="t d">
<title id="t">Shape morph</title>
<desc id="d">A blue outlined shape changes smoothly between a circle, a four-point star, a square, a triangle, a heart and a blob. Dashed outlines mark the starting and target shapes, and eight small dots mark the anchor points that travel between them.</desc>
<g transform="translate(80 14) scale(1.2)">
<path id="ghostA" class="ghost"/>
<path id="ghostB" class="ghost"/>
<path id="shape"/>
<g id="anchors"></g>
</g>
<text id="cap" class="cap" x="200" y="290" text-anchor="middle"></text>
</svg>
</div>
<div class="bar">
<label><span>From</span><select id="from"></select></label>
<label><span>To</span><select id="to"></select></label>
<label><span>Amount</span><input id="amt" type="range" min="0" max="1000" value="0"><output id="out">0%</output></label>
<button id="play" type="button">Pause</button>
</div>
</main>
<script src="../lab.js"></script>
<script src="demo.js"></script>
</body>
</html>
/lab/shape-morph/demo.js
(function () {
'use strict';
var $ = Lab.$;
var C = true; // corner flag
function polar(r, n, off) { var a = []; for (var i = 0; i < n; i++) { var t = (-90 + i * 360 / n) * Math.PI / 180; a.push([100 + r(i) * Math.cos(t), 100 + r(i) * Math.sin(t)]); } return a; }
var shapes = {
Circle: { pts: polar(function () { return 70; }, 8) },
Star: { pts: polar(function (i) { return i % 2 ? 32 : 84; }, 8), corner: C },
Square: { pts: [[100, 30], [170, 30], [170, 100], [170, 170], [100, 170], [30, 170], [30, 100], [30, 30]], corner: C },
Triangle: { pts: [[100, 28], [125.3, 72], [150.7, 116], [176, 160], [100, 160], [24, 160], [49.3, 116], [74.7, 72]], corner: C },
Heart: { pts: [[100, 62], [138, 34], [174, 70], [150, 122], [100, 172], [50, 122], [26, 70], [62, 34]], flags: [1, 0, 0, 0, 1, 0, 0, 0] },
Blob: { pts: polar(function (i) { return [62, 80, 58, 76, 66, 82, 56, 72][i]; }, 8) }
};
var names = Object.keys(shapes);
// Every shape becomes the same command list: M + 8 cubic segments, so numbers pair up one to one.
function build(s) {
var p = s.pts, n = 8, out = [p[0][0], p[0][1]];
function corner(i) { return s.corner || (s.flags && s.flags[i]); }
for (var i = 0; i < n; i++) {
var P = p[i], Q = p[(i + 1) % n], Pm = p[(i + n - 1) % n], Qn = p[(i + 2) % n], k = 0.1875;
var c1 = corner(i) ? P : [P[0] + (Q[0] - Pm[0]) * k, P[1] + (Q[1] - Pm[1]) * k];
var c2 = corner((i + 1) % n) ? Q : [Q[0] - (Qn[0] - P[0]) * k, Q[1] - (Qn[1] - P[1]) * k];
out.push(c1[0], c1[1], c2[0], c2[1], Q[0], Q[1]);
}
return out;
}
function toD(v) {
var f = function (x) { return x.toFixed(1); }, d = 'M' + f(v[0]) + ' ' + f(v[1]);
for (var i = 2; i < v.length; i += 6) d += 'C' + f(v[i]) + ' ' + f(v[i + 1]) + ' ' + f(v[i + 2]) + ' ' + f(v[i + 3]) + ' ' + f(v[i + 4]) + ' ' + f(v[i + 5]);
return d + 'Z';
}
var nums = {}; names.forEach(function (n) { nums[n] = build(shapes[n]); });
var from = $('#from'), to = $('#to'), amt = $('#amt'), out = $('#out'), play = $('#play');
names.forEach(function (n) { [from, to].forEach(function (s) { var o = document.createElement('option'); o.textContent = n; s.appendChild(o); }); });
var shape = $('#shape'), gA = $('#ghostA'), gB = $('#ghostB'), anchors = $('#anchors'), cap = $('#cap');
var dots = []; for (var i = 0; i < 8; i++) dots.push(Lab.make('circle', { r: 3.5, class: 'anchor' }, anchors));
var t = 0, hold = 0, auto = !Lab.reduced;
from.value = 'Circle'; to.value = 'Star';
if (!auto) t = 0.55;
function render() {
var A = nums[from.value], B = nums[to.value], e = Lab.ease(t), v = [];
for (var i = 0; i < A.length; i++) v.push(Lab.lerp(A[i], B[i], e));
shape.setAttribute('d', toD(v));
gA.setAttribute('d', toD(A)); gB.setAttribute('d', toD(B));
// anchors: point 0 is the start, then each segment ends at the next anchor
for (var k2 = 0; k2 < 8; k2++) { var idx = k2 === 0 ? 0 : 2 + 6 * (k2 - 1) + 4; dots[k2].setAttribute('cx', v[idx].toFixed(1)); dots[k2].setAttribute('cy', v[idx + 1].toFixed(1)); }
amt.value = Math.round(t * 1000); out.textContent = Math.round(t * 100) + '%';
amt.setAttribute('aria-valuetext', out.textContent);
cap.textContent = from.value + ' to ' + to.value + ': 1 move and 8 cubic curves each';
}
function setPlay(on) { auto = on; play.textContent = on ? 'Pause' : 'Play'; if (on) loop.start(); else loop.stop(); }
var loop = Lab.loop(function (dt) {
if (hold > 0) { hold -= dt; return; }
t += dt / 1.7;
if (t >= 1) {
t = 1; render(); hold = 0.7;
var next = names[(names.indexOf(to.value) + 1) % names.length];
from.value = to.value; to.value = next; t = 0; return;
}
render();
});
amt.addEventListener('input', function () { t = amt.value / 1000; setPlay(false); render(); });
from.addEventListener('change', render); to.addEventListener('change', render);
play.addEventListener('click', function () { setPlay(!auto); });
render(); setPlay(auto);
})();
/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}}