Javascript ChartJS:如何使用水平线制作条形图:
是否可以制作一个如下示例所示的图表 我还没有找到一个覆盖的例子。我在meteor应用程序中的atmosphere插件的上下文中使用了它,因此我可能无法轻松地将插件添加到我的chartjs实例中Javascript ChartJS:如何使用水平线制作条形图:,javascript,charts,chart.js,meteorcharts,Javascript,Charts,Chart.js,Meteorcharts,是否可以制作一个如下示例所示的图表 我还没有找到一个覆盖的例子。我在meteor应用程序中的atmosphere插件的上下文中使用了它,因此我可能无法轻松地将插件添加到我的chartjs实例中 我已经绘制了很多图表,因此,出于这个原因,我强烈建议将其转换到另一个图表库,但如果没有其他方法可以实现这一点,那么将它们移植过来还不算太晚。您可以扩展条形图以添加水平线 Chart.types.Bar.extend({ name: "BarLine", draw: fun
我已经绘制了很多图表,因此,出于这个原因,我强烈建议将其转换到另一个图表库,但如果没有其他方法可以实现这一点,那么将它们移植过来还不算太晚。您可以扩展条形图以添加水平线
Chart.types.Bar.extend({
name: "BarLine",
draw: function () {
Chart.types.Bar.prototype.draw.apply(this, arguments);
var scale = this.scale,
barHeight = this.scale.calculateY(83);
// draw line
this.chart.ctx.beginPath();
this.chart.ctx.moveTo(30, barHeight);
this.chart.ctx.strokeStyle = '#ff0000';
this.chart.ctx.lineWidth = 3;
this.chart.ctx.lineTo(this.chart.width, barHeight);
this.chart.ctx.stroke();
// write Label Text
this.chart.ctx.fillStyle = '#000000';
var text = this.options.labelText ? this.options.labelText : "DEFAULT TEXT"
this.chart.ctx.textAlign = 'center';
this.chart.ctx.font = '22px Arial';
this.chart.ctx.fillText(text, this.chart.width * 0.5, 95);
this.chart.ctx.closePath();
}
});`
我敢肯定,您可以在draw函数中添加条形图值,但我通常在图表的“onanimationcomplete”函数中添加条形图值,如下所示:
resultChart = new Chart(resultGraphCanvas.getContext("2d")).BarLine(chart, {
scaleBeginAtZero: true,
scaleOverride: true,
scaleSteps: 10,
scaleStepWidth: 10,
maintainAspectRatio: false,
labelText: "TEST DRAWN NEAR THE LINE",
showTooltips: false, //Needs to be set to false for the onAnimationComplete drawing to persist
onAnimationComplete: function () {
var ctx = this.chart.ctx;
ctx.font = this.scale.font;
ctx.fillStyle = this.scale.textColor
ctx.textAlign = "center";
ctx.textBaseline = "bottom";
this.datasets.forEach(function (dataset) {
dataset.bars.forEach(function (bar) {
ctx.fillText(bar.value, bar.x, bar.y );
});
})
},
});
这将在条的顶部绘制值,我将把它们放在其他位置留给您:)有趣。。。如果我是在Meteor+的环境中使用chartJS来制作很多其他有或没有指南的条形图,那么我就必须使用它。这里有很多值得思考的东西,如果我能将其抽象出来并使其发挥作用,我会回来标记为答案。我以前从未使用过Meteor,但不应该有任何理由(他说)这不起作用。您可以通过为条形图提供一个属性使其更具可配置性,该属性定义绘制水平线的级别。例如,出于某种原因,我没有看到labelText使其成为选项。知道那里发生了什么吗?更新了你的笔,现在一切正常。解释在代码中,重写图表时要访问的选项应作为第二个参数传入:)