这个例子是我在谷歌上找到的,它工作正常。当我们分别传递 x 和 y 值时,会在索引上创建垂直线。
example() {
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 = 'red';
ctx.lineTo(xaxis.getPixelForValue(undefined, index), yaxis.bottom);
ctx.stroke();
ctx.restore();
}
}
});
var config = {
type: 'line',
data: {
labels: ["January", "February", "March", "April", "May", "June", "July"],
datasets: [{
label: "My First dataset",
data: [12, 3, 2, 1, 8, 8, 2],
fill: false,
backgroundColor: 'blue',
borderColor: 'blue',
}],
lineAtIndex: [2,5]
},
};
new Chart('canvas', config);
}
这是我的代码,我正在尝试在图表上创建垂直线。这是显示股票市场代码表现的财务图表。我必须通过时间和价值观。
demochart() {
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 = 'red';
ctx.lineTo(xaxis.getPixelForValue(undefined, index), yaxis.bottom);
ctx.stroke();
ctx.restore();
}
}
});
var config = {
type: 'line',
data: {
datasets: [{
label: "My First dataset",
data: [{ x: 1591900200000, y: 1936.88 }, { x: 1592159400000, y: 379.38 },
{ x: 1592245800000, y: 2495.94 }, { x: 1592332200000, y: -938.44 },
{ x: 1592418600000, y: -1697.19 }, { x: 1592505000000, y: -1058.44 },
{ x: 1592764200000, y: 439.38 }, { x: 1592850600000, y: 758.75 }],
fill: false,
backgroundColor: 'blue',
borderColor: 'blue',
}],
lineAtIndex: 2
}
};
new Chart('canvas', config);
}