如何为chartjs栏中的每个条设置全长背景颜色
请参阅下面的链接我需要相同的输出 https://drive.google.com/file/d/0B4X0e4vwH_UPVGxWN2NBdURyZ0E/view?usp=sharing
答案 0 :(得分:4)
您可以调整其他答案,仅显示条形图的背景 - 请注意,在这种情况下,您需要条形图集合
Chart.types.Bar.extend({
name: "BarAlt",
initialize: function (data) {
var self = this;
var originalBuildScale = self.buildScale;
self.buildScale = function () {
originalBuildScale.apply(this, arguments);
var ctx = self.chart.ctx;
var scale = self.scale;
var originalScaleDraw = self.scale.draw;
var barAreaWidth = scale.calculateX(1) - scale.calculateX(0);
var barAreaHeight = scale.endPoint - scale.startPoint;
self.scale.draw = function () {
originalScaleDraw.call(this, arguments);
ctx.fillStyle = data.barBackground;
self.datasets.forEach(function (dataset) {
dataset.bars.forEach(function (bar) {
ctx.fillRect(
bar.x - bar.width / 2,
scale.startPoint,
bar.width,
barAreaHeight);
})
})
ctx.fill();
}
}
Chart.types.Bar.prototype.initialize.apply(this, arguments);
}
});
使用图表数据,如此
var data = {
barBackground: "rgba(221, 224, 229, 1)",
...
和这样的呼叫(如前所述)
var ctx = document.getElementById("chart").getContext("2d");
var myBarChart = new Chart(ctx).BarAlt(data, {
barValueSpacing: 15,
});
答案 1 :(得分:0)
您可以扩展条形图并覆盖缩放绘制事件以遮挡背景,如此
Chart.types.Bar.extend({
name: "BarAlt",
initialize: function (data) {
var self = this;
var originalBuildScale = self.buildScale;
self.buildScale = function () {
originalBuildScale.apply(this, arguments);
var ctx = self.chart.ctx;
var scale = self.scale;
var originalScaleDraw = self.scale.draw;
var barAreaWidth = scale.calculateX(1) - scale.calculateX(0);
var barAreaHeight = scale.endPoint - scale.startPoint;
self.scale.draw = function () {
originalScaleDraw.call(this, arguments);
scale.xLabels.forEach(function (xLabel, i) {
ctx.fillStyle = data.labelBackgrounds[i];
ctx.fillRect(
scale.calculateX(i - (scale.offsetGridLines ? 0.5 : 0)),
scale.startPoint,
barAreaWidth,
barAreaHeight);
ctx.fill();
})
}
}
Chart.types.Bar.prototype.initialize.apply(this, arguments);
}
});
使用图表数据,如此
var data = {
labelBackgrounds: ["rgba(120,220,220,0.2)", "rgba(220,120,220,0.2)", "rgba(220,220,120,0.2)", "rgba(120,120,220,0.2)", "rgba(120,220,120,0.2)", "rgba(220,120,120,0.2)", "rgba(120,120,120,0.2)"],
labels: ...
注意 - 如果你只想给酒吧上色,我相信已经有一个关于SO的问题。