如何使用html5画布绘制多级饼图?

时间:2016-09-27 13:14:03

标签: javascript jquery angularjs html5 html5-canvas

我正在尝试在pie-chart元素上创建canvas形状,但是我找不到任何能够自行完成此功能的函数。
有没有简单的方法来pie chart like below image

This pie indicates the progress of each slice

1 个答案:

答案 0 :(得分:1)

以下是使用可重复计算函数绘制弧线的起始示例:

请记住,首发&结束弧角为Radians。您可以将度数转换为如下弧度:radians = degrees * Math.PI/180



var canvas = document.getElementById("canvas");
var ctx = canvas.getContext("2d");
var cw=canvas.width;
var ch=canvas.height;
ctx.lineWidth = 2;
ctx.font = '14px verdana';

var PI2 = Math.PI * 2;
var myColor = ["Green", "Red", "Blue"];
var myData = [30, 15, 38, 22, 30, 20, 10];
var cx = 150;
var cy = 150;
var radius = 100;

ctx.globalAlpha=0.50;
pieChart(myData, myColor);
ctx.globalAlpha=1.00;

function pieChart(data, colors){
  // calc data total
  var total = 0;
  for (var i = 0; i < data.length; i++) {
    total += data[i];
  }
  // calc sweep angles for each piece of pie
  var sweeps = []
  for (var i = 0; i < data.length; i++) {
    sweeps.push(data[i] / total * PI2);
  }
  // draw outer pie
  var accumAngle = 0;
  for (var i = 0; i < sweeps.length; i++) {
    var f=randomColor();
    drawWedge(radius, accumAngle, accumAngle + sweeps[i], f, data[i]);
    accumAngle += sweeps[i];
  }
  // draw inner percent-complete wedges
  var accumAngle = 0;
  for (var i = 0; i < sweeps.length; i++) {
    var r=radius*(Math.random()*70+20)/100;
    var f=randomColor();
    drawWedge(r,accumAngle, accumAngle + sweeps[i], f, data[i]);
    accumAngle += sweeps[i];
  }  
}

function drawWedge(radius, startAngle, endAngle, fill, label) {
  // draw the wedge
  ctx.beginPath();
  ctx.moveTo(cx, cy);
  ctx.arc(cx, cy, radius, startAngle, endAngle, false);
  ctx.closePath();
  ctx.fillStyle = fill;
  ctx.strokeStyle = 'white';
  ctx.fill();
  ctx.stroke();
}

function randomColor(){ 
    return('#'+(Math.floor(Math.random() * 0x1000000) + 0x1000000).toString(16).substr(1));
}
&#13;
body{ background-color: ivory; }
#canvas{border:1px solid red; }
&#13;
<canvas id="canvas" width=512 height=512></canvas>
&#13;
&#13;
&#13;