如何知道SVG路径的绝对位置

How to know absolute position of a SVG PATH?

本文关键字:位置 路径 何知道 SVG      更新时间:2023-09-26

我有一个用InkScape生成的SVG,所有路径都移动到相对位置(m):

  <path xmlns="http://www.w3.org/2000/svg" 
        style="fill: #07fe01; 
               fill-opacity: 1; 
               display: inline; 
               stroke-width: 4px; 
               cursor: auto; 
               stroke: none; 
               opacity: 0.4; 
               filter: none; " 
         d="m 431.36764,202.65372 -20.46139,7.94003 -2.875,8.84375 -3.0625,13.21875 8.8125,0.96875 13.34375,6.84375 9.94451,-6.04527 11.96344,-1.95225 -2.3183,-6.56201 0.1291,-10.53422 z" 
         id="Rossello" 
         inkscape:connector-curvature="0"   xmlns:inkscape="http://www.inkscape.org/namespaces/inkscape" 
         sodipodi:nodetypes="ccccccccccc"  xmlns:sodipodi="http://sodipodi.sourceforge.net/DTD/sodipodi-0.dtd" 
         transform="translate(-0.03124997,-689.42566)" 
         onclick="mapmed.click(this)" 
         onmouseover="mapmed.over(this)" 
         onmouseout="mapmed.out(this)">
            <title id="title3042">Rosselló</title>
  </path>

我需要从javascript中知道每个路径的绝对位置,但我做不到。

在我看来,normalizedPathSegList就是您想要的。

试试这样的东西:

        ele=$('#Rosello')[0]
        var bbox = ele.getBBox()
        var top = bbox.y + bbox.y2

在x方向上也是如此。

我不确定,但我观察到getBBox相当慢。所以要小心。

我找到了一种知道绝对位置的方法。错误是试图在没有应用底层的情况下找到绝对坐标,像InkScape中那样从下到上平移和计数像素,而不是像SVG中那样从上到下。

按照这个陡度可以知道PATH的第一个节点的绝对位置(以像素为单位):

首先获取svg对象的宽度和高度。svgWidth,svgHeight。

第二,对基础布局进行变换平移。baseTransX,baseTransY。

第三个获取路径的第一个节点。路径X、路径Y。

第四,如果存在,如果不是0,则获取路径的变换平移。pathTransX、pathTransY。

有了这些值,我们可以找到InkScape:中第一个节点的绝对X和Y

X=baseTransX+pathTransX+pathX

Y=svgHeight-(baseTransY+pathTransY+pathY)