我正在使用Raphael.js构建一个自定义图表,其中包括弧线和百分比。圆弧的文本标签需要随圆弧移动。我通过使用 onAnimation 回调并获取外弧的点并相应地定位文本标签来实现这一点:
var paper = Raphael("paper", 200, 200);
var centerX = paper.width / 2;
var centerY = paper.height / 2;
// This is a dummy percentage; in real app this corresponds to actual value
var percentage = 0;
paper.customAttributes.arc = function(centerX, centerY, startAngle, endAngle, innerR, outerR) {
var radians = Math.PI / 180,
largeArc = +(endAngle - startAngle > 180),
outerX1 = centerX + outerR * Math.cos((startAngle - 90) * radians),
outerY1 = centerY + outerR * Math.sin((startAngle - 90) * radians),
outerX2 = centerX + outerR * Math.cos((endAngle - 90) * radians),
outerY2 = centerY + outerR * Math.sin((endAngle - 90) * radians),
innerX1 = centerX + innerR * Math.cos((endAngle - 90) * radians),
innerY1 = centerY + innerR * Math.sin((endAngle - 90) * radians),
innerX2 = centerX + innerR * Math.cos((startAngle - 90) * radians),
innerY2 = centerY + innerR * Math.sin((startAngle - 90) * radians);
var path = [
["M", outerX1, outerY1],
//move to the start point
["A", outerR, outerR, 0, largeArc, 1, outerX2, outerY2],
//draw the outer edge of the arc
["L", innerX1, innerY1],
//draw a line inwards to the start of the inner edge of the arc
["A", innerR, innerR, 0, largeArc, 0, innerX2, innerY2],
//draw the inner arc
["z"]
//close the path
];
return {
path: path
};
};
var arc = paper.path().attr({
'fill': "#cccccc",
'stroke': 'none',
'arc': [centerX, centerY, 0, 0, 60, 80]
});
arc.toBack();
var percentagesStart = 0;
var percentagesEnd = 0;
var percentagesDelta = 0;
var label = paper.text(
arc.attrs.path[1][6],
arc.attrs.path[1][7],
"0").toFront();
label.attr({
'font-size': 16,
'fill': "#000000",
'font-family': 'sans-serif',
'text-anchor': 'middle'
});
arc.onAnimation(function(anim) {
console.log("test");
label.attr({
x: this.attrs.path[1][6],
y: this.attrs.path[1][7],
text: (percentage++)
});
});
arc.animate({
'arc': [centerX, centerY, 0, 220, 60, 80]
}, 1000, 'easeInOut');
<script src="https://cdnjs.cloudflare.com/ajax/libs/raphael/2.1.4/raphael-min.js"></script>
<div id="paper"></div>
但是,文本标签必须位于圆弧结束的位置,并留有一些很好的边距。文本元素位置必须相对于弧进行转换。
我试过用
label.transform("t-10,10");
并尝试了其他一些 x、y 值,但这不起作用,因为在某些时候 x 值必须为负,而在某些时候 x 值必须为正,具体取决于弧的角度。
有没有办法正确定位它?