在饼图的外部区域添加边框

时间:2014-10-13 04:53:17

标签: javascript html5 html5-canvas

http://jsfiddle.net/wm7pwL2w/8/

如何在饼图的外部区域添加边框?请检查我的jsfiddle。我在这里实施了极地面积图。我需要每个边框都有不同的颜色,我可以指定。例如,请参阅此图片enter image description here

var canvas = document.getElementById("canvas");
var ctx = canvas.getContext('2d');
console.log(ctx);

var center = {
x: 200,
y: 150
};
var myColor = ["#ccc", "#ccc", "#ccc", "#ccc", "#c01c3f"];
var myData = [20, 40, 50, 70, 100];
var myRadius = [150, 120, 80, 100, 70];
var myDistance = [5, 5, 2, 2, 2];
var myText = ['first', 'second', 'third', 'fourth', 'fifth'];

function getTotal(data) {
var myTotal = 0;
for (var j = 0; j < data.length; j++) {
    myTotal += (typeof data[j] == 'number') ? data[j] : 0;
}
return myTotal;
}

function plotData() {
var lastend = 0;
var myTotal = getTotal(myData);

ctx.clearRect(0, 0, canvas.width, canvas.height);
ctx.textAlign = 'center';
ctx.textBaseline = 'middle';
//ctx.strokeStyle = 'rgba(255,255,255,0.5)';
ctx.lineWidth = 1;
ctx.font="15px Arial";
for (var i = 0; i < myData.length; i++) {
    ctx.save();
    ctx.fillStyle = myColor[i];
    ctx.beginPath();
    ctx.translate(center.x, center.y);
    var thisAngle = (Math.PI * 2 * (myData[i] / myTotal));
    ctx.rotate(lastend + thisAngle / 2);
    ctx.translate(myDistance[i], 0);
    ctx.moveTo(0, 0);
    ctx.arc(0, 0, myRadius[i], -(thisAngle / 2), thisAngle / 2, false);
    ctx.closePath();
    ctx.fill();
   // ctx.stroke();
    ctx.fillStyle = '#fff';
    ctx.translate(0.6 * myRadius[i], 0);
    ctx.rotate(-(lastend + thisAngle / 2));
    ctx.fillText(myText[i], 0, 0);
    ctx.restore();
    lastend += thisAngle;
}
}

plotData();

感谢所有帮助。

2 个答案:

答案 0 :(得分:3)

你需要分两步完成,首先填充形状,然后只是一个弧形。为此,您需要在填充后使用beginPath()作为外边框,以免划过整个形状。

...
ctx.closePath();
ctx.fill();
// original code stops

// insert this code
ctx.beginPath();
ctx.strokeStyle = '#079';
ctx.lineWidth = 9;
ctx.arc(0, 0, myRadius[i], -(thisAngle / 2), thisAngle / 2);
ctx.stroke();

// original code continues...
// ctx.stroke();
ctx.fillStyle = '#fff';
...

<强> Updated fiddle

答案 1 :(得分:0)

使用strokeStyle。 JSFiddle

var lineColor = ["blue", "green", "purple", "pink", "aqua"];
for (var i = 0; i < myData.length; i++) {
    ............................
    ctx.strokeStyle = lineColor[i];
    ctx.fillStyle = myColor[i];
    ........
    .............
    ctx.fill();
    ctx.stroke();
    ......................
}