获取 svg 元素的坐标返回 SVGAnimatedLength

gee*_*eeb 2 javascript svg dom

我尝试了一个简单的测试来理解 svg + JS 的行为,因为我需要检查某个 SVG 对象是否在 svg 路径上并采取相应的操作。当尝试显式访问 SVG 元素(在本例中为椭圆)的 .cx 或 .cy 属性时,我得到的是 SVGAnimatedLength 对象,而不是获取坐标。

<svg
   id="contenedorCirculo"
   width="200mm"
   height="200mm"
   viewBox="0 0 200 200"
   version="1.1"
>
<g
   inkscape:groupmode="layer"
   id="layer3"
   inkscape:label="points">
<ellipse
 style="fill:#ff00e5;fill-opacity:1;stroke:#fbde00;stroke-width:0;stroke-miterlimit:4;stroke-dasharray:none;stroke-opacity:1"
 id="circulo"
 cx="50"
 cy="50"
 rx="5"
 ry="5" />

</g>
</svg>

<script>
//this returns SVGAnimatedLength { baseVal: SVGLength, animVal: SVGLength }
console.log(document.getElementById("circulo").cx);

</script>
Run Code Online (Sandbox Code Playgroud)

Rob*_*son 6

您可能正在寻找价值。由于SMIL,许多 SVG 属性都有一个动画值和一个基本值。除非您实际上使用 SMIL,否则animValbaseVal是相同的

如果你想设置这个值,你应该设置baseVal; 只能animVal通过SMIL设置。

<svg
   id="contenedorCirculo"
   width="200mm"
   height="200mm"
   viewBox="0 0 200 200"
   version="1.1"
>
<g
   inkscape:groupmode="layer"
   id="layer3"
   inkscape:label="points">
<ellipse
 style="fill:#ff00e5;fill-opacity:1;stroke:#fbde00;stroke-width:0;stroke-miterlimit:4;stroke-dasharray:none;stroke-opacity:1"
 id="circulo"
 cx="50"
 cy="50"
 rx="5"
 ry="5" />

</g>
</svg>

<script>
//this returns SVGAnimatedLength { baseVal: SVGLength, animVal: SVGLength }
console.log(document.getElementById("circulo").cx.animVal.value);

</script>
Run Code Online (Sandbox Code Playgroud)