{
const svg = DOM.svg(300, 300);
const points = [
{ x: 50, y: 250 },
{ x: 100, y: 100 },
{ x: 150, y: 200 },
{ x: 200, y: 50 },
{ x: 250, y: 150 }
];
const duration = 4000;
const dotRadius = 5;
const polyline = document.createElementNS(
"http://www.w3.org/2000/svg",
"polyline"
);
polyline.setAttribute("points", points.map((p) => `${p.x},${p.y}`).join(" "));
polyline.setAttribute("fill", "none");
polyline.setAttribute("stroke", "black");
const dot = document.createElementNS("http://www.w3.org/2000/svg", "circle");
dot.setAttribute("cx", points[0].x);
dot.setAttribute("cy", points[0].y);
dot.setAttribute("r", dotRadius);
dot.setAttribute("fill", "red");
svg.appendChild(polyline);
svg.appendChild(dot);
let start = null;
let direction = 1;
function lerp(a, b, t) {
return {
x: a.x + (b.x - a.x) * t,
y: a.y + (b.y - a.y) * t
};
}
function animateDot(timestamp) {
if (!start) start = timestamp;
const elapsed = timestamp - start;
const totalDistance = points.length - 1;
const progress = (elapsed / duration) % 1;
const t =
direction === 1
? progress * totalDistance
: (1 - progress) * totalDistance;
const segment = Math.floor(t);
const segmentProgress = t - segment;
const a = points[segment];
const b = points[(segment + 1) % points.length];
const position = lerp(a, b, segmentProgress);
dot.setAttribute("cx", position.x);
dot.setAttribute("cy", position.y);
if (elapsed >= duration) {
direction *= -1;
start = timestamp;
}
requestAnimationFrame(animateDot);
}
requestAnimationFrame(animateDot);
return svg;
}