首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Chart.js 3.3.0 -在图表顶部绘制文本

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

Stack Overflow用户
提问于 2021-05-26 21:20:50
回答 1查看 838关注 0票数 1

我对JS非常陌生,我正在使用Chart.js v3构建一个图表。我正在寻找一种方法,把文字位在特定的x,y坐标在图表上,独立于任何数据点。我已经看到了一些以前版本的chart.js,like this one here的解决方案,但是还没能让它正常工作。

是否有任何方法可以通过chart.js实现这一点,或者我必须手动将文本元素添加到画布中?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2021-05-26 23:38:00

最好的做法是编写一个自定义插件,您可以将文本放在画布上,chart.js不提供这种功能。

示例:

​

代码语言:javascript
复制
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);
代码语言:javascript
复制
<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>

​

票数 5
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/67712875

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档