在特定 Y 值处绘制水平线
只需使用scale.calculateY 即可
var data = {
labels: ["JAN", "FEB", "MAR", "APR", "MAY", "JUN", "JUL", "AUG", "SEP", "OCT", "NOV", "DEC"],
datasets: [{
data: [12, 3, 2, 1, 8, 8, 2, 2, 3, 5, 7, 1]
}]
};
var ctx = document.getElementById("myChart").getContext("2d");
Chart.types.Line.extend({
name: "LineWithYLine",
draw: function () {
Chart.types.Line.prototype.draw.apply(this, arguments);
var scale = this.scale
var ctx = this.chart.ctx;
// calculate using the scale
var y = scale.calculateY(this.options.lineAtValue);
// draw line
ctx.save();
ctx.strokeStyle = '#ff0000';
ctx.beginPath();
ctx.moveTo(Math.round(scale.xScalePaddingLeft), y);
ctx.lineTo(this.chart.width, y);
ctx.stroke();
ctx.restore();
}
});
new Chart(ctx).LineWithYLine(data, {
datasetFill: false,
lineAtValue: 7.5
});
如果要绘制标签,可以调整行尾位置留出空间。然后使用相同的 y 值在那里绘制文本。
如果您的图表数据点无法使刻度拉伸足够大(例如,刻度是从 0 到 10,但您想在 12 处绘制一条线),请使用 chart.js 选项来覆盖刻度。
小提琴 - http://jsfiddle.net/gywzg9e4/