Pie Chart w/ Legend

chart.js pie chart with rendered percentage inside pie

by Luis Martin

HTML

<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/1.0.1/Chart.min.js"></script>
<div class="chart">
	<canvas id="property_types" class="pie"></canvas>
	<div id="pie_legend"></div>
</div>

CSS

.pie-legend {
	list-style: none;
	margin: 0;
	padding: 0;
}
.pie-legend span {
	display: inline-block;
	width: 14px;
	height: 14px;
	border-radius: 100%;
	margin-right: 16px;
	margin-bottom: -2px;
}
.pie-legend li {
	margin-bottom: 10px;
}

JavaScript

// global options variable
	var options = {
		responsive: true,
		scaleBeginAtZero: true,
        // you don't have to define this here, it exists inside the global defaults
		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>",
    tooltipTemplate: "<%= value + ' %' %>",
    onAnimationProgress: drawSegmentValues
	}
  Chart.defaults.global.showTooltips = false;

		// PIE
		// PROPERTY TYPE DISTRIBUTION
		// context
		var ctxPTD = $("#property_types").get(0).getContext("2d");
		// data
		var dataPTD = [
			{
				label: "Single Family Residence",
				color: "#5093ce",
				highlight: "#78acd9",
				value: 52
			},
			{
				label: "Townhouse/Condo",
				color: "#c7ccd1",
				highlight: "#e3e6e8",
				value: 12
			},
			{
				label: "Land",
				color: "#7fc77f",
				highlight: "#a3d7a3",
				value: 6
			},
			{
				label: "Multifamily",
				color: "#fab657",
				highlight: "#fbcb88",
				value: 8
			},
			{
				label: "Farm/Ranch",
				color: "#eaaede",
				highlight: "#f5d6ef",
				value: 8
			},
			{
				label: "Commercial",
				color: "#dd6864",
				highlight: "#e6918e",
				value: 14
			},
			
		]

		// Property Type Distribution
		var propertyTypes = new Chart(ctxPTD).Pie(dataPTD, options);
			// pie chart legend
			$("#pie_legend").html(propertyTypes.generateLegend());

var radius = propertyTypes.outerRadius;

var canvas = document.getElementById("property_types");

var midX = canvas.width/2;
var midY = canvas.height/2

function drawSegmentValues()
{
    for(var i=0; i<propertyTypes.segments.length; i++) 
    {
        // Default properties for text (size is scaled)
        ctxPTD.fillStyle="white";
        var textSize = canvas.width/21;
        ctxPTD.font= textSize+"px Verdana";

        // Get needed variables
        var value = propertyTypes.segments[i].value;
    ...