DME*_*MEM 5 javascript css label chart.js
我正在使用 Chart.js,并且尝试将饼图上的标签移到饼图区域之外(请参见红色 X):
这是我现在的代码:
<div class="container" id="pieContainer">
<h4 class="title">Title</h4>
<center><canvas id="pie"></canvas></center>
</div>
<script>
var pieData = [
{
value: 39,
color:"#335478",
label: "Blue"
},
{
value : 4,
color : "#7f7f7f",
label: "Grey"
},
{
value : 57,
color : "#99cb55",
label: "Green"
}
];
var optionsPie = {
responsive : true,
tooltipEvents: [],
showTooltips: true,
onAnimationComplete: function() {
this.showTooltip(this.segments, true);
},
tooltipTemplate: "<%= label %> - <%= value %>%"
};
new Chart(document.getElementById("pie").getContext("2d")).Pie(pieData, optionsPie);
</script>
Run Code Online (Sandbox Code Playgroud)
我不想使用图例,而且找不到移动标签的内置方法。有没有办法在不改变的情况下做到这一点chart.js?实现我的目标的最佳方法是什么?
只需扩展图表即可完成此操作。如果您的标签是静态的,则更改tooltipPosition方法可能会更简单。
预览
脚本
Chart.types.Pie.extend({
name: "PieAlt",
initialize: function(data){
Chart.types.Pie.prototype.initialize.apply(this, arguments);
var requiredSpace = 0;
for (var i = 0; i < data.length; i++)
requiredSpace = Math.max(ctx.measureText(Chart.helpers.template(this.options.tooltipTemplate, data[i])).width, requiredSpace);
this.outerRadius -= (requiredSpace + 20);
},
draw: function(data){
Chart.types.Pie.prototype.draw.apply(this, arguments);
var self = this;
ctx.save();
ctx.font = Chart.helpers.fontString(self.options.scaleFontSize, self.options.scaleFontStyle, self.options.scaleFontFamily);
ctx.textBaseline = "middle";
self.segments.forEach(function (segment) {
var outerEdge = Chart.Arc.prototype.tooltipPosition.apply({
x: this.chart.width / 2,
y: this.chart.height / 2,
startAngle: segment.startAngle,
endAngle: segment.endAngle,
outerRadius: segment.outerRadius * 2 + 20,
innerRadius: 0
})
var normalizedAngle = (segment.startAngle + segment.endAngle) / 2;
while (normalizedAngle > 2 * Math.PI) {
normalizedAngle -= (2 * Math.PI)
}
if (normalizedAngle < (Math.PI * 0.4) || (normalizedAngle > Math.PI * 1.5))
ctx.textAlign = "start";
else if (normalizedAngle > (Math.PI * 0.4) && (normalizedAngle < Math.PI * 0.6)) {
outerEdge.y += 5;
ctx.textAlign = "center";
}
else if (normalizedAngle > (Math.PI * 1.4) && (normalizedAngle < Math.PI * 1.6)) {
outerEdge.y - 5;
ctx.textAlign = "center";
}
else
ctx.textAlign = "end";
ctx.fillText(Chart.helpers.template(self.options.tooltipTemplate, segment), outerEdge.x, outerEdge.y);
});
ctx.restore();
}
});
Run Code Online (Sandbox Code Playgroud)
进而
new Chart(ctx).PieAlt(data, {
showTooltips: false
});
Run Code Online (Sandbox Code Playgroud)
小提琴 - http://jsfiddle.net/h8rggkhp/