Progress ring fills each segment with a sweep instead of redrawing
This commit is contained in:
+35
-9
@@ -174,20 +174,46 @@ export function ring(n, total, size = 160, label = `${n}/${total}`) {
|
||||
const r = 40, sw = 10, c = 2 * Math.PI * r;
|
||||
// round caps overhang sw/2 on each side, so shorten each dash by sw
|
||||
const slot = c / total, gap = total > 1 ? 5 : 0, seg = slot - gap - sw;
|
||||
const at = (len) => { const a = -Math.PI / 2 + len / r; return `${50 + r * Math.cos(a)} ${50 + r * Math.sin(a)}`; };
|
||||
const fills = [];
|
||||
for (let i = 0; i < total; i++) {
|
||||
const el = document.createElementNS(SVGNS, "circle");
|
||||
el.setAttribute("cx", 50); el.setAttribute("cy", 50); el.setAttribute("r", r);
|
||||
el.setAttribute("stroke-width", sw);
|
||||
el.setAttribute("stroke-dasharray", `${seg} ${c - seg}`);
|
||||
// start at 12 o'clock
|
||||
el.setAttribute("stroke-dashoffset", String(c / 4 - i * slot - (gap + sw) / 2));
|
||||
el.setAttribute("class", "seg" + (i < n ? " on" : "") + (i === n - 1 && n < total ? " last" : ""));
|
||||
svg.append(el);
|
||||
const s0 = i * slot + (gap + sw) / 2;
|
||||
const d = `M ${at(s0)} A ${r} ${r} 0 ${seg / r > Math.PI ? 1 : 0} 1 ${at(s0 + seg)}`;
|
||||
// track underneath, fill on top sweeps clockwise through pathLength 1
|
||||
for (const cls of ["seg", "fill"]) {
|
||||
const el = document.createElementNS(SVGNS, "path");
|
||||
el.setAttribute("d", d);
|
||||
el.setAttribute("stroke-width", sw);
|
||||
el.setAttribute("class", cls);
|
||||
if (cls === "fill") { el.setAttribute("pathLength", 1); fills.push(el); }
|
||||
svg.append(el);
|
||||
}
|
||||
}
|
||||
const t = document.createElementNS(SVGNS, "text");
|
||||
t.setAttribute("x", 50); t.setAttribute("y", 50);
|
||||
t.setAttribute("text-anchor", "middle"); t.setAttribute("dominant-baseline", "central");
|
||||
t.textContent = label;
|
||||
svg.append(t);
|
||||
// updates in place so the css transitions run
|
||||
svg.set = (k, text = `${k}/${total}`) => {
|
||||
fills.forEach((el, i) => {
|
||||
el.classList.toggle("on", i < k);
|
||||
el.classList.toggle("last", i === k - 1 && k < total);
|
||||
});
|
||||
t.textContent = text;
|
||||
};
|
||||
svg.total = total;
|
||||
svg.set(n, label);
|
||||
return svg;
|
||||
}
|
||||
|
||||
// keeps the same svg between counts so each new segment fills instead of popping in
|
||||
export function paintRing(box, n, total, size) {
|
||||
let svg = box.querySelector("svg.ring");
|
||||
if (!svg || svg.total !== total) {
|
||||
svg = ring(0, total, size);
|
||||
box.replaceChildren(svg);
|
||||
// one frame at the old count, so the first fill animates too
|
||||
svg.getBoundingClientRect();
|
||||
}
|
||||
svg.set(n);
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user