HTML5 Canvas pie chart

前端 未结 4 1131
名媛妹妹
名媛妹妹 2020-12-05 07:30

I\'m attempting to create a simple pie chart like shown in the graphic below:

\"enter<

4条回答
  •  暖寄归人
    2020-12-05 07:47

    Even after searching Google and triple-checking my radians values, etc. I was still having trouble with this, so I have created a jsFiddle for people to play with as a live example and will post the code below as well. (Update: in the fiddle v2, stroke and labels are added also.)

    var canvas = document.getElementById("can");
    var ctx = canvas.getContext("2d");
    var lastend = 0;
    var data = [200, 60, 15]; // If you add more data values make sure you add more colors
    var myTotal = 0; // Automatically calculated so don't touch
    var myColor = ['red', 'green', 'blue']; // Colors of each slice
    
    for (var e = 0; e < data.length; e++) {
      myTotal += data[e];
    }
    
    for (var i = 0; i < data.length; i++) {
      ctx.fillStyle = myColor[i];
      ctx.beginPath();
      ctx.moveTo(canvas.width / 2, canvas.height / 2);
      // Arc Parameters: x, y, radius, startingAngle (radians), endingAngle (radians), antiClockwise (boolean)
      ctx.arc(canvas.width / 2, canvas.height / 2, canvas.height / 2, lastend, lastend + (Math.PI * 2 * (data[i] / myTotal)), false);
      ctx.lineTo(canvas.width / 2, canvas.height / 2);
      ctx.fill();
      lastend += Math.PI * 2 * (data[i] / myTotal);
    }

提交回复
热议问题