教程 chartjs tutorial

动画与交互

Chart.js 支持丰富的动画效果和交互配置。你可以为图表加载设置动画,也可以定义动画完成的回调函数,实现更复杂的交互行为。同时,图表支持鼠标悬停、点击等事件响应,使用户能够与图表更好地交互。

js
(function () {
  const ctx = document.getElementById("animationChart").getContext("2d");
  new Chart(ctx, {
    type: "line",
    data: {
      labels: ["一月", "二月", "三月", "四月", "五月"],
      datasets: [
        {
          label: "销量趋势",
          data: [10, 20, 15, 30, 25],
          borderColor: "rgb(54, 162, 235)",
          fill: false,
          tension: 0.4,
        },
      ],
    },
    options: {
      responsive: true,
      animation: {
        duration: 2000,
        easing: "easeInOutQuart",
        onComplete: function () {
          console.log("动画完成!");
        },
      },
      interaction: {
        mode: "nearest",
        axis: "x",
        intersect: false,
      },
      plugins: {
        tooltip: {
          enabled: true,
        },
      },
      onClick: (event, elements) => {
        if (elements.length) {
          const index = elements[0].index;
          alert(`点击了:${index + 1} 月`);
        }
      },
    },
  });
})();
在线代码演示
源码
<!DOCTYPE html>
<html lang="zh">

<head> <meta charset="UTF-8"> <title>Chart.js 动画与交互</title> <script src="https://cdn.jsdelivr.net/npm/chart.js&quot;&gt;&lt;/script&gt; <style> body { max-width: 700px; margin: 2rem auto; background: #f9f9f9; padding: 1rem; font-family: sans-serif; }

canvas {
  background: #fff;
  border: 1px solid #ccc;
  display: block;
  margin: 0 auto;
}

</style> </head>

<body> <canvas id="animationChart" width="700" height="400"></canvas> <script> (function () { const ctx = document.getElementById(‘animationChart’).getContext(‘2d’); new Chart(ctx, { type: ‘line’, data: { labels: [‘一月’, ‘二月’, ‘三月’, ‘四月’, ‘五月’], datasets: [{ label: ‘销量趋势’, data: [10, 20, 15, 30, 25], borderColor: ‘rgb(54, 162, 235)’, fill: false, tension: 0.4 }] }, options: { responsive: true, animation: { duration: 2000, easing: ‘easeInOutQuart’, onComplete: function () { console.log(‘动画完成!’); } }, interaction: { mode: ‘nearest’, axis: ‘x’, intersect: false }, plugins: { tooltip: { enabled: true } }, onClick: (event, elements) => { if (elements.length) { const index = elements[0].index; alert(点击了:${index + 1} 月); } } } }); })(); </script> </body>

</html>