2017-10-05 72 views
0

我创建了饼图,一切看起来都很棒,但我无法在饼图的每个部分中插入文本,如“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>  

回答

0

嗨,我已编辑您的代码。你必须用Cosinus(X Axis)和Sinus(Y Axis)来计算每个片段的位置,并用cancas.getContext(“2d).fillText(”text“,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

但是使用帆布,你可以使用海图 Pie Diagramm with Highchart

+0

哇它像一个魅力的作品谢谢我将检查HIghChart插件谢谢 – lkh

相关问题