Categories
JavaScript Answers

How to add a HTML5 Canvas pie chart with JavaScript?

Spread the love

Sometimes, we want to add a HTML5 Canvas pie chart with JavaScript.

In this article, we’ll look at how to add a HTML5 Canvas pie chart with JavaScript.

How to add a HTML5 Canvas pie chart with JavaScript?

To add a HTML5 Canvas pie chart with JavaScript, we can use the canvas moveTo, arc, lineTo, and fill methods.

For instance, we write:

<canvas id="can" width="200" height="200" />

to add a canvas element.

Then we write:

const canvas = document.getElementById("can");
const ctx = canvas.getContext("2d");
let lastend = 0;
const data = [200, 60, 15];
const myTotal = data.reduce((a, b) => a + b, 0);
const myColor = ['red', 'green', 'blue'];

for (const [i, d] of data.entries()) {
  ctx.fillStyle = myColor[i];
  ctx.beginPath();
  ctx.moveTo(canvas.width / 2, canvas.height / 2);
  ctx.arc(canvas.width / 2, canvas.height / 2, canvas.height / 2, lastend, lastend + (Math.PI * 2 * (d / myTotal)), false);
  ctx.lineTo(canvas.width / 2, canvas.height / 2);
  ctx.fill();
  lastend += Math.PI * 2 * (d / myTotal);
}

We select the canvas element with document.getElementById.

Then we get the context with getContext.

Next, we loop through the data entries with a for-of loop to add the pie slices.

To add the slice, we call beginPath to start drawing.

Then we call moveTo to move to the coordinates we want to start drawing.

Next, we call arc to draw the arc with the width, height and angle.

Then we call lineTo to move the line to the end of the slice.

Finally, we call fill to fill the chart with the fillStyle color.

And then we repeat this with all the data entries.

Conclusion

To add a HTML5 Canvas pie chart with JavaScript, we can use the canvas moveTo, arc, lineTo, and fill methods.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *