首页 > 解决方案 > Chart.js 3.3.0 - 在图表顶部绘制文本

问题描述

我对 JS 很陌生,我正在使用 Chart.js v3 构建图表。我正在寻找一种将文本位放置在图表上特定 x,y 坐标处的方法,独立于任何数据点。我已经看到了一些针对以前版本的 chart.js 的解决方案,比如这里的这个,但一直无法让它工作。

有什么方法可以通过chart.js 实现这一点,还是我必须手动将文本元素添加到画布?

标签: javascriptchart.js

解决方案


最好的办法是编写一个自定义插件,您可以在其中将文本放在画布上,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);
<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>


推荐阅读