首页 > 解决方案 > 从javascript中的字符串确定svg元素的边界框

问题描述

如果我在 chrome 中加载 SVG,我可以得到它的元素的边界框,如下所示: document.getElementById('char1').getBBox() -> SVGRect {x: 348.5628356933594, y: 78.95916748046875, width: 202.74807739257812, height: 845.1696166992188}

但是,如果我使用 DOMParser 加载相同的 SVG,我会得到一个值为 0 的边界框。

例如:

const svgString = document.documentElement.outerHTML // in practice this would be an svg fetched from elsewhere
let svgElement = new DOMParser().parseFromString(svgString, 'text/xml').documentElement
svgElement.getElementById('char1').getBBox()

->

SVGRect {x: 0, y: 0, width: 0, height: 0}

a) 为什么会这样?b)如何通过使用 svg 字符串而不将其加载到文档中来获得正确的边界框值?

标签: javascripthtmlsvg

解决方案


推荐阅读