效果图:

 

html:

<canvas id="canvas" width="500" height="500"></canvas>

js:

var data = [
  { name: '第一期', num: 500, color: '#ff9273' },
  { name: '第二期', num: 300, color: '#2ed6b9' },
  { name: '第三期', num: 900, color: '#3ba2f2' },
  { name: '第四期', num: 700, color: '#ffcc4d' },
  { name: '第五期', num: 300, color: '#2ed6b9' },
  { name: '第六期', num: 700, color: '#ffcc4d' },
];
chart(data, 'canvas');

function chart(a,b){
  var canvas = document.getElementById(b);
  var ctx = canvas.getContext('2d');
  var deg = Math.PI / 180;
  var end_deg = 0;
  var star_deg = -90;
  var total = 0;
  var width = canvas.width;
  var height = canvas.height;
  
  for(var i = 0; i < a.length; i++) {
    total += a[i].num - 0;
  }
  function getX(n, r) {
    return r * Math.sin(n * ((2 * Math.PI) / 360));
  }

  function getY(n, r) {
    return r * Math.cos(n * ((2 * Math.PI) / 360));
  }

  for(var i = 0; i < a.length; i++) {
    end_deg = (a[i].num - 0) / total * 360;

    ctx.beginPath();
    ctx.moveTo(width / 2, height / 2);
    ctx.arc(width / 2, height / 2, height * 0.3, star_deg * deg, (star_deg + end_deg) * deg, false);
    ctx.fillStyle = a[i].color;
    ctx.fill();

    ctx.beginPath()
    var x0 = width / 2 + getY(star_deg + end_deg / 2, height * 0.3);
    var y0 = height / 2 + getX(star_deg + end_deg / 2, height * 0.3);
    var x1 = width / 2 + getY(star_deg + end_deg / 2, height * 0.3 + 20);
    var y1 = height / 2 + getX(star_deg + end_deg / 2, height * 0.3 + 20);
    ctx.moveTo(x0, y0);
    ctx.lineTo(x1, y1)
    ctx.strokeStyle = a[i].color
    ctx.stroke()

    ctx.beginPath()
    if(x0 > x1) {
      ctx.textAlign = 'left'
      var x2 = x0 - ctx.measureText(data[i].name).width - 30
    } else {
      ctx.textAlign = 'right'
      var x2 = x0 + ctx.measureText(data[i].name).width + 30
    }
    ctx.moveTo(x1, y1);
    ctx.lineTo(x2, y1);
    ctx.font="20px Arial";
    ctx.fillText(a[i].name, x2, y1 - 4)
    ctx.strokeStyle = a[i].color;
    ctx.stroke();

    star_deg += end_deg;
  }
};

 

posted on 2018-07-02 10:51  YC小杨  阅读(164)  评论(0编辑  收藏  举报