画布饼图内的标签

时间:2015-03-21 03:44:32

标签: javascript html5-canvas pie-chart

我正在使用canvas创建一个饼图,但我无法将标签放入画布中。我尝试了很多东西......你能帮助我吗?

HTML

<canvas id="can" width="200" height="200" />

JS

var D1 = 15;
var D2 = 15;
var D3 = 45;
var D4 = 25;
var canvas = document.getElementById("can");
var ctx = canvas.getContext("2d");
var lastend = 0;
var data = [D1,D2,D3,D4]; // If you add more data values make sure you add more colors
var myTotal = 0; // Automatically calculated so don't touch
var myColor = ["#ECD078","#D95B43","#C02942","#542437"];
var labels = ["25%","25%","25%","25%"];

for (var e = 0; e < data.length; e++) {
  myTotal += data[e];
  ctx.font = 'bold 15pt Calibri';
  ctx.fillText(labels[e],15,15);
}

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);
}

我的目的是在饼图内按顺序放置labels[]数字。

2 个答案:

答案 0 :(得分:1)

如果还不晚,你可以试试这个: https://jsfiddle.net/rradik/kuqdwuyd/

object

可能不是完美且非常有效的,但仍然可以完成工作

答案 1 :(得分:0)

问题是你的所有文字都重叠了。

我只是改变了执行顺序。现在,在饼图之后绘制文本。还有一件事,我在文本中添加了一个偏移量,每次循环运行时我都会偏移50。

Working Example

var offset = 50;
for (var e = 0; e < data.length; e++) {
    ctx.font = 'bold 15pt Calibri';
    ctx.fillText(labels[e],offset*e,180);
}