转换文本元素相对于Raphael.js中路径的位置

时间:2012-05-07 08:52:52

标签: javascript svg raphael

我正在使用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值必须为正,具体取决于弧的角度。

有没有办法正确定位?

0 个答案:

没有答案