How to make a pie chart in CSS

前端 未结 6 1471
天命终不由人
天命终不由人 2021-01-30 22:58

How can I create a pie chart with CSS like the one below?

\"enter

6条回答
  •  礼貌的吻别
    2021-01-30 23:47

    Often Creating charts with pure css is not the best way. it's better to use canvas or external libraries.

    Here is a pie chart without using external libraries, using html5 canvas (fiddle) :

    var canvas = document.getElementById("can");
    var ctx = canvas.getContext("2d");
    var lastend = 0;
    var data = [60,210,90];
    var myTotal = 0;
    var myColor = ['#afcc4c', '#95b524','#c1dd54'];
    var labels = ['B', 'A', 'C'];
    
    for(var e = 0; e < data.length; e++)
    {
      myTotal += data[e];
    }
    
    // make the chart 10 px smaller to fit on canvas
    var off = 10
    var w = (canvas.width - off) / 2
    var h = (canvas.height - off) / 2
    for (var i = 0; i < data.length; i++) {
      ctx.fillStyle = myColor[i];
      ctx.strokeStyle ='white';
      ctx.lineWidth = 2;
      ctx.beginPath();
      ctx.moveTo(w,h);
      var len =  (data[i]/myTotal) * 2 * Math.PI
      var r = h - off / 2
      ctx.arc(w , h, r, lastend,lastend + len,false);
      ctx.lineTo(w,h);
      ctx.fill();
      ctx.stroke();
      ctx.fillStyle ='white';
      ctx.font = "20px Arial";
      ctx.textAlign = "center";
      ctx.textBaseline = "middle";
      var mid = lastend + len / 2
      ctx.fillText(labels[i],w + Math.cos(mid) * (r/2) , h + Math.sin(mid) * (r/2));
      lastend += Math.PI*2*(data[i]/myTotal);
    }
    html, body{
      background: #c4c9e9
    }
      

    fiddle (code is written based on this solution)

    But it's better to use libraries for drawing charts. in apex-charts there is an option called sparkline, which helps you to remove the extra stuffs and draw a minimal and clean chart.

    Here is a clean donut chart using apex-charts library. (Extra stuffs are removed with sparkline option):

    var options = {
      series: [620, 40],
      labels: ['Finished', 'Unfinished'],
      chart: {
        type: 'donut',
        sparkline: {
          enabled: true,
        }
      },
      plotOptions: {
        pie: {
          donut: {
            labels: {
              show: true,
              total: {
                showAlways: false,
                show: true,
                label: 'Total'
              }
            }
          }
        }
      },
    };
    var chart = new ApexCharts(document.querySelector("#chart"), options);
    chart.render();
    
    

    See it on codepen

提交回复
热议问题