Skip to content

Instantly share code, notes, and snippets.

@frankfuu
Last active January 28, 2016 14:32
Show Gist options
  • Save frankfuu/392aaeb75d9d0bf53907 to your computer and use it in GitHub Desktop.
Save frankfuu/392aaeb75d9d0bf53907 to your computer and use it in GitHub Desktop.
An alternative version of the chart type named Doughnut in Chart.js
(function () {
// An alternative version of the chart type Doughnut in Chart.js
Chart.types.Doughnut.extend({
name: "DoughnutAlt",
defaults: this.defaultConfig,
draw: function () {
Chart.types.Doughnut.prototype.draw.apply(this, arguments);
this.chart.ctx.fillStyle = 'black';
this.chart.ctx.textBaseline = 'middle';
this.chart.ctx.textAlign = 'start';
this.chart.ctx.font = "18px Verdana";
var total = 0;
for (var i = 0; i < this.segments.length; i++) {
total += this.segments[i].value;
}
for (var i = 0; i < this.segments.length; i++) {
var percentage = ((this.segments[i].value / total) * 100).toFixed(1);
if (percentage > 3) {
var centreAngle = this.segments[i].startAngle + ((this.segments[i].endAngle - this.segments[i].startAngle) / 2),
rangeFromCentre = (this.segments[i].outerRadius - this.segments[i].innerRadius) / 2 + this.segments[i].innerRadius;
var x = this.segments[i].x + (Math.cos(centreAngle) * rangeFromCentre);
var y = this.segments[i].y + (Math.sin(centreAngle) * rangeFromCentre);
this.chart.ctx.textAlign = 'center';
this.chart.ctx.textBaseline = 'middle';
this.chart.ctx.fillStyle = '#fff';
this.chart.ctx.font = 'normal 10px Helvetica';
this.chart.ctx.fillText(percentage, x, y);
}
}
}
});
// calling it with options (http://www.chartjs.org/docs/#line-chart-chart-options)
var options = {
responsive: true,
animationEasing: "fadeIn",
tooltipTemplate: "<%if (label){%><%=label%>: <%}%><%= value %>%",
legendTemplate : "<ul class=\"<%=name.toLowerCase()%>-legend\"><% for (var i=0; i<segments.length; i++){%><li><span style=\"background-color:<%=segments[i].fillColor%>\"></span><%if(segments[i].label){%><%=segments[i].label%><%}%></li><%}%></ul>"
};
var ctx = document.getElementById("my-chart").getContext("2d");
var mychart = new Chart(ctx).DoughnutAlt(doughnutData, options);
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment