Pie chart - Donut

by kapilgopinath

HTML

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.1/jquery.min.js"></script>
<div class="flx">
  <div>
    <label>Angry</label>
    <input class="Angry" value="1499"/>
  </div>
  <div>
    <label>Happy</label>
    <input class="Happy" value="478"/>
  </div>
  <div>
    <label>Melancholic</label>
    <input class="Melancholic" value="332"/>
  </div>
  <div>
    <label>Gloomy</label>
    <input class="Gloomy" value="195"/>
  </div>
</div>

<div class="container">
<canvas width="200" height="200"></canvas>
</div>

CSS

.container {
          width: 100%;
          height: 100vh;
          display: flex;
          justify-content: center;
          align-items: center;
        }
        .flx{
          display: flex;
        }

JavaScript

let ctx = document.querySelector("canvas").getContext("2d");

    const results = [
        {mood: "Angry", total: 1499, shade: "#0a9627"},
        {mood: "Happy", total: 478, shade: "#960A2C"},
        {mood: "Melancholic", total:332, shade: "#332E2E"},
        {mood: "Gloomy", total: 195, shade: "#F73809"}
    ];
    $(function(){
    renderPie();
    $('input').on('input', (e) => {
     let clsNm = e.target.className,
          moodVal = e.target.value,
          resultObj = results.find(mood => mood.mood === clsNm);
          resultObj.total = Number(moodVal);
     renderPie();     
     console.log(clsNm, moodVal)
    })
    function renderPie() {

    let sum = 0;
    let totalNumberOfPeople = results.reduce((sum, {total}) => sum + total, 0);
    let currentAngle = 0;
    let i = 0;
    console.log(results)
   for (let moodValue of results) {
        //calculating the angle the slice (portion) will take in the chart
        let portionAngle = (moodValue.total / totalNumberOfPeople) * 2 * Math.PI;
        //drawing an arc and a line to the center to differentiate the slice from the rest
        ctx.beginPath();
        ctx.arc(100, 100, 100, currentAngle, currentAngle + portionAngle);
        currentAngle += portionAngle;
        ctx.lineTo(100, 100);
        //filling the slices with the corresponding mood's color
        ctx.fillStyle = moodValue.shade;
        ctx.fill();
       // if (i === 1)
       // break;
        i++
    }
    ctx.beginPath();
    ctx.arc(100, 100, 50, 0, 360);
    ctx.fillStyle = '#ff0';
    ctx.fill();
    }
    })