Chart.js 2.0 - 垂直线 [英] Chart.js 2.0 - vertical lines
本文介绍了Chart.js 2.0 - 垂直线的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
谁能告诉我如何扩展 Chart.js v2.0.我需要折线图中的垂直线,我想实现类似于
<小时>脚本
var originalLineDraw = Chart.controllers.line.prototype.draw;Chart.helpers.extend(Chart.controllers.line.prototype, {画:函数(){originalLineDraw.apply(this, arguments);var 图表 = this.chart;var ctx = 图表.chart.ctx;var index = chart.config.data.lineAtIndex;如果(索引){var xaxis = chart.scales['x-axis-0'];var yaxis = chart.scales['y-axis-0'];ctx.save();ctx.beginPath();ctx.moveTo(xaxis.getPixelForValue(undefined, index), yaxis.top);ctx.strokeStyle = '#ff0000';ctx.lineTo(xaxis.getPixelForValue(undefined, index), yaxis.bottom);ctx.stroke();ctx.restore();}}});
然后
var config = {类型:'线',数据: {标签: ...数据集:[...],lineAtIndex:2}};
<小时>
小提琴 - http://jsfiddle.net/mn8x6fso/
Can anyone tell me how to extend Chart.js v2.0. I need vertical lines in a line chart and I want to implement something similar to http://jsfiddle.net/dbyze2ga/.
Chart.types.Line.extend({
name: "LineWithLine",
draw: function () {
Chart.types.Line.prototype.draw.apply(this, arguments);
var point = this.datasets[0].points[this.options.lineAtIndex]
var scale = this.scale
// draw line
this.chart.ctx.beginPath();
this.chart.ctx.moveTo(point.x, scale.startPoint + 24);
this.chart.ctx.strokeStyle = '#ff0000';
this.chart.ctx.lineTo(point.x, scale.endPoint);
this.chart.ctx.stroke();
// write TODAY
this.chart.ctx.textAlign = 'center';
this.chart.ctx.fillText("TODAY", point.x, scale.startPoint + 12);
}
});
new Chart(ctx).LineWithLine(data, {
datasetFill : false,
lineAtIndex: 2
});
解决方案
UPDATE: See https://stackoverflow.com/a/45092928/360067 for a simpler and more robust solution using the Chart Annotations plugin.
You can extend the line
type to add support for drawing a line
Preview
Script
var originalLineDraw = Chart.controllers.line.prototype.draw;
Chart.helpers.extend(Chart.controllers.line.prototype, {
draw: function() {
originalLineDraw.apply(this, arguments);
var chart = this.chart;
var ctx = chart.chart.ctx;
var index = chart.config.data.lineAtIndex;
if (index) {
var xaxis = chart.scales['x-axis-0'];
var yaxis = chart.scales['y-axis-0'];
ctx.save();
ctx.beginPath();
ctx.moveTo(xaxis.getPixelForValue(undefined, index), yaxis.top);
ctx.strokeStyle = '#ff0000';
ctx.lineTo(xaxis.getPixelForValue(undefined, index), yaxis.bottom);
ctx.stroke();
ctx.restore();
}
}
});
and then
var config = {
type: 'line',
data: {
labels: ...
datasets: [
...
],
lineAtIndex: 2
}
};
Fiddle - http://jsfiddle.net/mn8x6fso/
这篇关于Chart.js 2.0 - 垂直线的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文