变换后的矩形坐标

Thy*_*hys 9 html javascript svg

我目前正在绘制一个矩形,在其父元素(g)上进行转换.由此产生的svg是这样的;

<svg version="1.1" width="1055" height="381">
   <g transform="rotate(120)">
      <rect x="0" y="0" width="100" height="100" rx="10" ry="0" stroke-width="0" style="stroke:rgb(0,0,0)" id="rect-0"></rect>
      <rect x="100" y="0" width="100" height="100" rx="10" ry="0" stroke-width="0" style="stroke:rgb(0,0,0)" id="rect-1"></rect>
   </g>
</svg> 
Run Code Online (Sandbox Code Playgroud)

现在我试图动态检索其中一个rects的坐标,但使用getBBox不会返回正确的结果.任何人都可以告诉我如何获得其中一个rect的正确x,y,宽度和高度属性?

Thy*_*hys 18

我自己找到了解决方案;

var matrix = shape.getCTM();

// transform a point using the transformed matrix
var position = svg.createSVGPoint();
position.x = $(shape).attr("x");
position.y = $(shape).attr("y");
position = position.matrixTransform(matrix);
Run Code Online (Sandbox Code Playgroud)

  • 我一直在寻找3天,正是为了这个功能,大声笑。我不知道为什么其他答案不使用它。 (2认同)