Create a pie chart using JavaScript.

Create a pie chart using JavaScript

Today, We learn to create a pie chart without any library. This post will take you through how to do that using JavaScript, HTML Canvas, and CSS.

Pre-Requirements

  1. HTML
  2. CSS
  3. JavaScript

Create a pie chart full code:

<!DOCTYPE html>
<html>
<head>
    <title>canvas test</title>
    <style type="text/css">
        .pie_container{ width: 100%; height: 100vh; display: flex; justify-content: center; align-items: center;}
    </style>
</head>
<body>
<div class="pie_container">
<canvas width="200" height="200"></canvas>
</div>
</body>
<script>
    let ibctx = document.querySelector("canvas").getContext("2d");
    const dataChart = [
        {mood: "Angry", total: 32, shade: "orange"},
        {mood: "Happy", total: 20, shade: "#13cd3b"},
        {mood: "Melancholic", total:16, shade: "#4f1c93"}
    ];
    let sum = 0;
    let currentAngle = 0;
    let totalNumberOfPart = dataChart.reduce((sum, {total}) => sum + total, 0);

    for (let moodValue of dataChart) {        
        let portionAngle = (moodValue.total / totalNumberOfPart) * 2 * Math.PI;        
        ibctx.beginPath();
        ibctx.arc(100, 100, 100, currentAngle, currentAngle + portionAngle);
        currentAngle += portionAngle;
        ibctx.lineTo(100, 100);        
        ibctx.fillStyle = moodValue.shade;
        ibctx.fill();
    }
</script></html>

lineTo()
This method is used to draw a straight line.
It is used together with the beginPath() and moveTo() to create a line.

arc()

We pass in the center’s x and y coordinates, the radius’ length, and the angles where the arc will start and where it will end.

Related Post Top 5 Hosting Providers In India

Like us on Facebook and Linkedin for more updates.

Leave a Reply

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

Back To Top