Я хочу получить координату (top, left)
элемента text
относительно элемента svg
, выраженную в той же единице / величине, что и атрибуты y
и x
элемента text
.
Я думаю, что пример ниже близок, но есть проблема. getBoundingClientRect
возвращает различные значения для top, left
при изменении размера порта просмотра, в то время как, конечно, значения атрибута y, x
элемента text
всегда одинаковы. Таким образом, единицы / величие top, left
и y, x
не совпадают.
Я попытался установить display: flex
на теле, чтобы заставить svg не масштабироваться, но затем он получил размер 0 x 0.
const svgRect = document.querySelector("svg").getBoundingClientRect()
const textRect = document.querySelector("text").getBoundingClientRect()
const textBoxPosRelativeToSvgExpressedInSvgCoordinates = {top: textRect.y - svgRect.y, left: textRect.x - svgRect.x}
console.log(textBoxPosRelativeToSvgExpressedInSvgCoordinates)
<body>
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 600 400">
<g id="main">
<line x1="10" y1="10" x2="100" y2="200" stroke="#00c" stroke-width="5" stroke-linecap="round"/>
<polyline points="580,10 560,390 540,200 520,390 400,390" stroke="#c00" stroke-width="5" stroke-linecap="round" stroke-linejoin="round" fill="none"/>
<polygon points="350,75 379,161 469,161 397,215 423,301 350,250 277,301 303,215 231,161 321,161" stroke="#ff0" stroke-width="10" fill="#ffc"/>
<rect x="100" y="10" width="150" height="100" rx="10" ry="20" stroke="#060" stroke-width="8" fill="#0f0"/>
<circle cx="100" cy="300" r="80" stroke="#909" stroke-width="10" fill="#f6f"/>
<ellipse cx="450" cy="50" rx="80" ry="30" stroke="#0cc" stroke-width="10" fill="#0ff"/>
<text x="240" y="390" font-family="sans-serif" font-size="50" fill="#00f">SVG</text>
</g>
</svg>
</body>