如何在饼图中添加文本?

时间:2017-10-05 10:22:26

标签: javascript pie-chart

我创建了饼图,一切看起来都不错,但我无法在饼图的每个部分插入文本,例如“data 1”“data 2” 。我知道有填充文本方法,但在这种情况下,我无法用x位置和y位置填充文本。你有什么想法吗?

<!DOCTYPE html>
<html>
<body>

<canvas id="myCanvas" width="600" height="600" style="border:1px solid #d3d3d3;">
</canvas>

<script>

function draw() {
  var canvas = document.getElementById("myCanvas");
  var ctx = canvas.getContext("2d");

  // Colors
  var colors = ['red', 'green', 'yellow', 'black', 'purple'];


  // store beginning angle and ending angle 
  var beginAngle = 0;
  var endAngle = 0;
  // data input 
  var data =[10,10,10,10,10]
  var total = 0;
  //sum of data
  for(i=0;i<data.length;i++){
    total = total + data[i];

  }
  // Iterate through the angles
  for(var i = 0; i < data.length; i = i + 1) {
    beginAngle= endAngle;//begin angle
    endAngle = endAngle+((Math.PI*2)*(data[i]/total));//end angle

    ctx.beginPath();
    // Fill color
    ctx.fillStyle = colors[i];

    //create each arc of the pie chart
    ctx.moveTo(200, 200);
    ctx.arc(200, 200, 120, beginAngle,endAngle);
    ctx.lineTo(200, 200);
    ctx.stroke();

    // Fill
    ctx.fill();
  }
}
window.onload = draw;


</script>


</body>
</html>       

1 个答案:

答案 0 :(得分:0)

您好我编辑了您的代码。您必须使用Cosinus(X轴)和Sinus(Y轴)来计算每个部分的位置,并使用cancas.getContext(&#34; 2d).fillText(&#34; text&#34;,x,y)

<强> HTML

<body>
<canvas id="myCanvas" width="400" height="400" style="border:1px solid 
#d3d3d3;">
</canvas>
</body>

<强> JS

function draw() {
var canvas = document.getElementById("myCanvas");
var ctx = canvas.getContext("2d");

// Colors
var colors = ['red', 'green', 'yellow', 'black', 'purple'];


// store beginning angle and ending angle 
var beginAngle = 0;
var endAngle = 0;
// data input 
var data = [10, 10, 10, 10, 10]
var total = 0;
//sum of data
for (i = 0; i < data.length; i++) {
    total = total + data[i];

}
// Iterate through the angles
for (var i = 0; i < data.length; i = i + 1) {
    beginAngle = endAngle; //begin angle
    endAngle = endAngle + ((Math.PI * 2) * (data[i] / total)); //end angle

    ctx.beginPath();
    // Fill color
    ctx.fillStyle = colors[i];
    //create each arc of the pie chart
    ctx.moveTo(200, 200);
    ctx.arc(200, 200, 120, beginAngle, endAngle);
    ctx.lineTo(200, 200);
    ctx.stroke();
    ctx.fill()

    // Set Text
    var pieRadius = Math.min(ctx.canvas.width / 2, ctx.canvas.height / 2);
    var labelX = ctx.canvas.width / 2 + (pieRadius / 2) * Math.cos(beginAngle + (endAngle - beginAngle) / 2);
    var labelY = ctx.canvas.height / 2 + (pieRadius / 2) * Math.sin(beginAngle + (endAngle - beginAngle) / 2)
    ctx.fillStyle = "white";
    ctx.font = "bold 10px Arial";
    ctx.fillText("test", labelX, labelY);

    // Fill
}
}
draw()

Working fiddle

但是使用Canvas可以使用Highchart Pie Diagramm with Highchart