Chart.js - 如何在图表中间添加文本? [英] Chart.js - How to Add Text in the Middle of the Chart?

查看:37
本文介绍了Chart.js - 如何在图表中间添加文本?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 Chart.js 创建这个折线图:

I'm using Chart.js to create this line chart:

但我需要标记区域,如下所示:

But I need to label the zones, something like this:

有什么想法吗?

推荐答案

你扩展你使用的图表,然后使用辅助方法编写标签

You extend the chart which you used and then write the labels using the helper methods

HTML

<canvas id="myChart" width="500" height="400"></canvas>

在下面的JS中,注意calculateY的参数是y value,而calculateX是标签索引

In the below JS, note that the parameter to calculateY is the y value, while for calculateX, it is label index

Chart.types.Line.extend({
  name: "LineAlt",
  draw: function(){
    Chart.types.Line.prototype.draw.apply(this, arguments);

    this.chart.ctx.textAlign = "center"
    // y value and x index
    this.chart.ctx.fillText("ZONE1", this.scale.calculateX(3.5), this.scale.calculateY(20.75))
    this.chart.ctx.fillText("ZONE2", this.scale.calculateX(11.5), this.scale.calculateY(13))
    this.chart.ctx.fillText("ZONE3", this.scale.calculateX(2), this.scale.calculateY(9.75))
    this.chart.ctx.fillText("ZONE4", this.scale.calculateX(14.5), this.scale.calculateY(22.75))
  }
});

var data = {
  labels: [8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24],
  datasets: [{
    data: []
  }]
};

var ctx = document.getElementById("myChart").getContext("2d");
var myBarChart = new Chart(ctx).LineAlt(data, {
  scaleOverride: true,
  scaleSteps: 16,
  scaleStepWidth: 1,
  scaleStartValue: 8,
  animation: false
});

小提琴 - https://jsfiddle.net/bpfvvxpn/

不确定您是如何创建折线图的,所以没有将其添加到小提琴中

Not sure how you created the line chart, so didn't add it to the fiddle

这篇关于Chart.js - 如何在图表中间添加文本?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆