教程 chartjs tutorial

自定义 Tooltip

Chart.js 提供了强大的 Tooltip 自定义功能。通过配置 options.plugins.tooltip,可以自定义 Tooltip 的显示内容、格式、样式等,满足不同场景需求。

以下示例演示如何使用回调函数自定义 Tooltip 显示的文本格式,包括添加单位和自定义标题。

js
const ctx = document.getElementById("customTooltipChart").getContext("2d");

new Chart(ctx, {
  type: "line",
  data: {
    labels: ["一月", "二月", "三月", "四月", "五月"],
    datasets: [
      {
        label: "温度",
        data: [3, 6, 9, 7, 5],
        borderColor: "rgb(255, 99, 132)",
        backgroundColor: "rgba(255, 99, 132, 0.5)",
        fill: false,
        tension: 0.1,
      },
    ],
  },
  options: {
    responsive: true,
    plugins: {
      tooltip: {
        callbacks: {
          title: function (context) {
            return "月份:" + context[0].label;
          },
          label: function (context) {
            return "温度:" + context.parsed.y + " °C";
          },
        },
      },
      legend: {
        display: true,
      },
    },
  },
});
在线代码演示
源码
<!DOCTYPE html>
<html lang="zh">

<head> <meta charset="UTF-8" /> <title>自定义 Tooltip 示例</title> <script src="https://cdn.jsdelivr.net/npm/chart.js&quot;&gt;&lt;/script&gt; <style> body { max-width: 700px; margin: 2rem auto; font-family: sans-serif; background: #f9f9f9; padding: 1rem; text-align: center; }

canvas {
  background: #fff;
  border: 1px solid #ccc;
  margin: 1rem auto;
}

</style> </head>

<body> <canvas id="customTooltipChart" width="700" height="400"></canvas> <script> (function () { const ctx = document.getElementById(‘customTooltipChart’).getContext(‘2d’);

  new Chart(ctx, {
    type: 'line',
    data: {
      labels: ['一月', '二月', '三月', '四月', '五月'],
      datasets: [{
        label: '温度',
        data: [3, 6, 9, 7, 5],
        borderColor: 'rgb(255, 99, 132)',
        backgroundColor: 'rgba(255, 99, 132, 0.5)',
        fill: false,
        tension: 0.1
      }]
    },
    options: {
      responsive: true,
      plugins: {
        tooltip: {
          callbacks: {
            title: function (context) {
              return '月份:' + context[0].label;
            },
            label: function (context) {
              return '温度:' + context.parsed.y + ' °C';
            }
          }
        },
        legend: {
          display: true
        }
      }
    }
  });
})();

</script> </body>

</html>