javascript - 在 ChartJS 中添加背景文本

标签 javascript css chart.js

我想在所有图表绘图后面的 ChartJS 中心添加一个信息背景文本。除了使用此处所示的图像之外,还有其他方法吗:How can i add an image as background in Chartjs?

问候,

最佳答案

您可以扩展Chartdraw() 函数来向图表添加文本。然后,您可以通过计算图表中间的 x 和 y 值或指定它们来控制文本的位置,具体取决于图表的呈现方式:

let myLineExtend = Chart.controllers.line.prototype.draw;
Chart.helpers.extend(Chart.controllers.line.prototype, {
  draw: function() {
    myLineExtend.apply(this, arguments);
    // text styles below
    this.chart.chart.ctx.textAlign = "center"
    this.chart.chart.ctx.font = "20px Arial black";
    this.chart.chart.ctx.fillText("Lorem Ipsum Blah Blah", 300, 150)  // text, x-pos, y-pos
  }
});

这是一个演示这一点的片段:

let myLineExtend = Chart.controllers.line.prototype.draw;

let 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: {
    scales: {
      yAxes: [{
        ticks: {
          reverse: false
        }
      }]
    }
  }
}

let ctx = document.getElementById('container').getContext('2d');
Chart.helpers.extend(Chart.controllers.line.prototype, {
  draw: function() {
    myLineExtend.apply(this, arguments);
    this.chart.chart.ctx.textAlign = "center"
    this.chart.chart.ctx.font = "20px Arial black";
    this.chart.chart.ctx.fillText("Lorem Ipsum Blah Blah", 300, 150)
  }
});

new Chart(ctx, options);
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.3.0/Chart.js"></script>

<body>
  <canvas id="container" width="600" height="400"></canvas>
</body>

关于javascript - 在 ChartJS 中添加背景文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57567325/

相关文章:

javascript - 从字符串中提取泛型类型参数

Javascript - 如果字符串包含并替换

html - 表的表类,当太宽时将所有单元格拆分成行

chart.js - Chartjs 刻度线颜色为零时不同

javascript - Chart.js 不遵守我的容器尺寸

javascript - 无法使用脚本自动填充 PHP MYSQL 动态表(文本字段)中的值

javascript - PDFJS.PDFLinkService 不是一个函数

html div元素内容超出div

html - Bootstrap 3 单选按钮覆盖标签

javascript - 在 Chart.js 中使用范围条形图可视化间隔