Chart.js 3.3.0 - 在图表顶部绘制文本

1 javascript chart.js

我对 JS 很陌生,我正在使用 Chart.js v3 构建图表。我正在寻找一种方法,将文本位放置在图表上的特定 x,y 坐标处,独立于任何数据点。我已经看到了针对先前版本的 Chart.js 的一些解决方案,例如此处的解决方案,但未能使其正常工作。

有没有办法通过 Chart.js 实现这一点,或者我必须手动将文本元素添加到画布上?

Lee*_*lee 6

最好的办法是编写一个自定义插件,您可以将文本放在画布上,chart.js 不提供开箱即用的此功能

例子:

const customText = {
  id: 'customText',
  afterDraw: (chart, args, options) => {
    const {
      ctx,
      canvas
    } = chart;
    textObjects = options.text;

    if (textObjects.length === 0) {
      return;
    }

    textObjects.forEach((textObj) => {
      ctx.save();

      ctx.textAlign = textObj.textAlign || 'center';
      ctx.font = `${textObj.size || '20px'} ${textObj.font || 'Arial'}`;
      ctx.fillStyle = textObj.color || 'black'
      ctx.fillText(textObj.text, textObj.x, textObj.y)

      ctx.restore();
    })
  }
}

const options = {
  type: 'line',
  data: {
    labels: ["Red", "Blue", "Yellow", "Green", "Purple", "Orange"],
    datasets: [{
        label: '# of Votes',
        data: [12, 19, 3, 5, 2, 3],
        borderWidth: 1
      },
      {
        label: '# of Points',
        data: [7, 11, 5, 8, 3, 7],
        borderWidth: 1
      }
    ]
  },
  options: {
    plugins: {
      customText: {
        text: [{
            text: 'Lorem ipsum',
            x: 300,
            y: 150,
            textAlign: 'center',
            size: '30px',
            color: 'black',
            font: 'Arial black'
          },
          {
            text: 'Lorem ipsum2',
            x: 300,
            y: 250,
            textAlign: 'center',
            color: 'red',
            font: 'Arial black'
          }
        ]
      }
    }
  },
  plugins: [customText]
}

const ctx = document.getElementById('chartJSContainer').getContext('2d');
new Chart(ctx, options);
Run Code Online (Sandbox Code Playgroud)
<body>
  <canvas id="chartJSContainer" width="600" height="400"></canvas>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/3.3.0/chart.js"></script>
</body>
Run Code Online (Sandbox Code Playgroud)