我正在研究chartjs(版本2.7.2)。我想创建一个具有边界半径的条形图(' barradius'根据chartjs选项)。
像这样:
我为barradius:4
设置了值,但它无效。
HTML:
<canvas id="myChart" width="400" height="200"></canvas>
使用Javascript:
var canvas = document.getElementById('myChart');
var data = {
labels: ["January", "February", "March", "April", "May", "June", "July"],
datasets: [
{
label: "My First dataset",
backgroundColor: "rgba(255,99,132,0.2)",
borderColor: "rgba(255,99,132,1)",
borderWidth: 2,
hoverBackgroundColor: "rgba(255,99,132,0.4)",
hoverBorderColor: "rgba(255,99,132,1)",
data: [65, 59, 20, 81, 56, 55, 40],
}
]
};
var option = {
title: {
display: false,
},
tooltips: {
intersect: false,
mode: 'nearest',
xPadding: 10,
yPadding: 10,
caretPadding: 10
},
legend: {
display: false
},
responsive: true,
maintainAspectRatio: false,
barRadius: 4,
scales: {
xAxes: [{
display: false,
gridLines: false,
stacked: true
}],
yAxes: [{
display: false,
stacked: true,
gridLines: false
}]
},
layout: {
padding: {
left: 0,
right: 0,
top: 0,
bottom: 0
}
}
};
var myBarChart = Chart.Bar(canvas, {
data: data,
options: option
});
var myBarChart = Chart.Bar(canvas, {
data: data,
options: option
});
答案 0 :(得分:3)
就我在类似问题中看到的那样,解决方案应该是扩展Chart.types.Bar.extend
https://jsfiddle.net/hyacinthe/t8khnL4q/
Chart.types.Bar.extend({
name: "BarAlt",
initialize: function (data) {
Chart.types.Bar.prototype.initialize.apply(this, arguments);
if (this.options.curvature !== undefined && this.options.curvature <= 1) {
var rectangleDraw = this.datasets[0].bars[0].draw;
var self = this;
var radius = this.datasets[0].bars[0].width * this.options.curvature * 0.2;
// override the rectangle draw with ours
this.datasets.forEach(function (dataset) {
dataset.bars.forEach(function (bar) {
bar.draw = function () {
// draw the original bar a little down (so that our curve brings it to its original position)
var y = bar.y;
// the min is required so animation does not start from below the axes
bar.y = Math.min(bar.y + radius, self.scale.endPoint - 1);
// adjust the bar radius depending on how much of a curve we can draw
var barRadius = (bar.y - y);
rectangleDraw.apply(bar, arguments);
// draw a rounded rectangle on top
Chart.helpers.drawRoundedRectangle(self.chart.ctx, bar.x - bar.width / 2, bar.y - barRadius + 1, bar.width, bar.height, barRadius);
ctx.fill();
// restore the y value
bar.y = y;
}
})
})
}
}
});
这个答案归功于@potatopeelings。