如何在 svg 中查找文本的坐标

How to find the coordinates of a text in an svg?

本文关键字:文本 坐标 查找 svg      更新时间:2023-09-26

我有一个svg,它有一些形状和一些文字。 我想要的是特定文本的坐标和ID。 比如:

<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" width="1010px" height="750px" viewBox="0 0  1010 750" preserveAspectRatio="xMidYMid meet" zoomAndPan="disable" >
<rect x="104" y="85" stroke="black" id="e1_rectangle" style="stroke-width: 1px; vector-effect: non-scaling-stroke;" width="145" height="209" fill="red"/> 
<text fill="black" x="346" y="147" id="e2_texte" style="font-family: Arial; font-size: 20px;" transform="matrix(1 0 0 1 -217 -80)">rectangle</text>           
<circle id="e5_circle" cx="407" cy="166" stroke="black" style="stroke-width: 1px; vector-effect: non-scaling-stroke;" r="83.0963296422" fill="green"/>  
<text fill="black" x="387" y="62" id="e6_texte" style="font-family: Arial; font-size: 20px;" >circle</text>  
</svg>                                   

现在,如果我想知道文本的 x,y 坐标:"矩形",我该怎么做呢?

谢谢

您可以使用(因为它标记的)d3 来做到这一点。

//filter all the texts
var texts = d3.selectAll("text")[0].filter(function(r) {
  return d3.select(r).text() == "rectangle"
})
//map all the x and y of filtered texts
var coordinates = texts.map(function(t){
    return {x: d3.select(t).attr("x"), y : d3.select(t).attr("y")}
})
console.log(coordinates)

工作代码在这里