将 Chart JS 2 上的条形图扩展为一种新型 Chart
我实际上是在使用 Chart JS 2.0.1 在页面上绘制图表.
I'm actualy using Chart JS 2.0.1 to draw charts on a page.
我的客户要求我在条形图中添加一条线,以便他们可以看到无法超过的限制.像这样:y轴上的条形图
My customers asked me to add a line in a bar chart so that they can see the limit they can't go over. Like that: Bar chart with line on y axes
因此,我正在尝试将条形图扩展为一个新的条形图,该条形图采用一个名为 lineAtValue 的参数,该参数提供该线的 y 值.
So, I'm trying to extend the Bar Chart into a new one which takes a parameter called lineAtValue which provides the y value for the line.
我成功扩展了条形图,但它覆盖了页面中显示的其他条形图,而我在其他条形图中不需要它.
I succeeded in extending the bar chart but it overrides the others bar charts displayed in the page and I don't need that in the other Bar Charts.
这是我所做的:http://jsfiddle.net/d5ye1xpe/
我希望能够有这样的东西:jsfiddle.net/L3uhpvd5/(对不起,我不能上传两个以上的链接)
And I'd like to be able to have something like this one : jsfiddle.net/L3uhpvd5/ (sorry I can't upload more than two links) with the
Chart.barWithLine(ctx,config);
但是使用 Chart JS 的 2.0.1 版本
But with the version 2.0.1 of Chart JS
谢谢,
普图尔内姆
推荐答案
这很有帮助,但我发现它并没有针对实际上不是数据的行添加新数据集进行优化.
This is helpful but I found it not that optimized to add new Dataset just for a line that is actually not a data.
我终于成功地创建了扩展 bar 类型的新类型,如果提供了值,则添加一行.
I finally suceeded in creating the new type that extend the bar type and add a line if the value is provided.
// Store the original Draw function
var originalLineDraw = Chart.controllers.bar.prototype.draw;
// extend the new type
Chart.helpers.extend(Chart.controllers.bar.prototype, {
draw: function () {
// use the base draw function
originalLineDraw.apply(this, arguments);
// get chart and context
var chart = this.chart;
var ctx = chart.chart.ctx;
// get lineAtValue value
var value = chart.config.lineAtValue;
// stop if it doesn't exist
if (typeof value === "undefined") {
return;
}
// draw the line
var xaxis = chart.scales['x-axis-0'];
var yaxis = chart.scales['y-axis-0'];
ctx.save();
ctx.beginPath();
ctx.moveTo(xaxis.left, yaxis.getPixelForValue(value));
ctx.strokeStyle = '#ff0000';
ctx.lineTo(xaxis.right, yaxis.getPixelForValue(value));
ctx.stroke();
ctx.restore();
}
});
但感谢您的帮助 =)
相关文章