HTML5 Canvas | Draw Donut Chart

html5-canvas-donut-chart-1Drawing in HTML5 is really interesting you can draw almost everything if you master the tricks of drawing. Here we will draw a donut chart using arc() function then we will give it some artistic effects using gradient color and shadow. You need to know some basic simple math concepts about circle to draw such chart.




Using HTML5 standard functions you can draw points, line, rectangles, circles and even text. Here since we are trying to draw donut shape “or circles” we will use arc() function.

arc() function needs to know 6 things. X & Y of the center of the circle or arc, radius, start and end points in radian and direction of drawing clockwise (true) or counter-clockwise (false).


<!DOCTYPE html>
		<canvas id="myCanvas" width="360" height="360" style="border:1px solid #d3d3d3;">
			Your browser does not support the HTML5 canvas tag.
		<script type="text/javascript">
			var X = 180;
			var Y = 180;
			var outterRadius = 150;
			var innerRadius = 110;

			// 1. get a reference to myCanvas element.
			var c = document.getElementById("myCanvas");
			// 2. get canvas context
			var context = c.getContext("2d");
			// 3. draw donut chart
			// RED
			setRadialGradient("#DC1C29", "#B7161B");
			drawDonut(Math.PI * 0.32, Math.PI * 0.5);
			// GREEN
			setRadialGradient("#84BC3D", "#5B8829");
			drawDonut(Math.PI*0.5 , Math.PI* 1.5);
			// BLUE
			setRadialGradient("#27A1D4", "#2182AD");
			drawDonut(Math.PI * 1.5, Math.PI*2);
			// YELLOW
			setRadialGradient("#ECCF2D", "#F1C433");
			drawDonut(0, Math.PI*.32);
			// drawDonut() function drawes 2 full or partial circles inside each other one clockwise and the other is counter-clockwise
			function drawDonut(sRadian, eRadian){
					context.arc(X, Y, outterRadius, sRadian, eRadian, false); // Outer: CCW
					context.arc(X, Y, innerRadius, eRadian, sRadian, true); // Inner: CW
				// add shadow
			function addShadow(){
				context.shadowColor = "#333";
				context.shadowBlur = 5;
				context.shadowOffsetX = 0;
				context.shadowOffsetY = 0;
			function setRadialGradient(sgc, bgc){
				var grd = context.createRadialGradient(X, Y, innerRadius + 5, X, Y, outterRadius);
				context.fillStyle = grd;

Leave a Reply