教程 chartjs tutorial

自定义插件

Chart.js 支持通过插件机制扩展功能。自定义插件可以在图表的不同生命周期钩子里执行代码,比如绘制前、绘制后、更新时等,实现特殊效果或业务需求。

下面示例演示一个简单插件,在图表绘制后在画布上绘制一段文字水印。

js
(function () {
  const watermarkPlugin = {
    id: "watermark",
    afterDraw(chart) {
      const ctx = chart.ctx;
      ctx.save();
      ctx.font = "bold 24px Arial";
      ctx.fillStyle = "rgba(0, 0, 0, 0.1)";
      ctx.textAlign = "center";
      ctx.fillText("Chart.js 教程水印", chart.width / 2, chart.height / 2);
      ctx.restore();
    },
  };

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

  new Chart(ctx, {
    type: "bar",
    data: {
      labels: ["一月", "二月", "三月", "四月"],
      datasets: [
        {
          label: "销售额",
          data: [30, 50, 70, 60],
          backgroundColor: "rgba(75, 192, 192, 0.7)",
        },
      ],
    },
    options: {
      responsive: true,
      plugins: {
        legend: { display: true },
      },
    },
    plugins: [watermarkPlugin],
  });
})();
在线代码演示
源码
<!DOCTYPE html>
<html lang="zh">

<head> <meta charset="UTF-8" /> <title>自定义插件</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="pluginChart" width="700" height="400"></canvas> <script> (function () { const watermarkPlugin = { id: ‘watermark’, afterDraw(chart) { const ctx = chart.ctx; ctx.save(); ctx.font = ‘bold 24px Arial’; ctx.fillStyle = ‘rgba(0, 0, 0, 0.1)’; ctx.textAlign = ‘center’; ctx.fillText(‘Chart.js 教程水印’, chart.width / 2, chart.height / 2); ctx.restore(); } };

  const ctx = document.getElementById('pluginChart').getContext('2d');

  new Chart(ctx, {
    type: 'bar',
    data: {
      labels: ['一月', '二月', '三月', '四月'],
      datasets: [{
        label: '销售额',
        data: [30, 50, 70, 60],
        backgroundColor: 'rgba(75, 192, 192, 0.7)'
      }]
    },
    options: {
      responsive: true,
      plugins: {
        legend: { display: true }
      }
    },
    plugins: [watermarkPlugin]
  });
})();

</script> </body>

</html>