line-chart

互動折線圖

用原生 SVG 與假資料做出可互動的折線圖。

這個 demo 用內建假資料產生 SVG path,滑過圖表時會找出最近的資料點並更新標籤。

原始碼
const data = [18, 22, 19, 28, 34, 31, 42, 39, 48, 51, 47, 58];
const points = data.map((value, index) => ({
  x: 36 + (index / (data.length - 1)) * 648,
  y: 324 - ((value - Math.min(...data)) / (Math.max(...data) - Math.min(...data))) * 288,
  value,
}));

svg.addEventListener('pointermove', (event) => {
  const x = ((event.clientX - svg.getBoundingClientRect().left) / svg.clientWidth) * 720;
  const nearest = points.reduce((best, point) =>
    Math.abs(point.x - x) < Math.abs(best.x - x) ? point : best,
  );
  tooltip.textContent = nearest.value;
});