将 SVG 高度和宽度设置为其内部 <text> 节点的高度和宽度

Set SVG height and width to that of the <text> node inside it

有没有办法使 SVG 元素的宽度和高度等于其中 text 节点内文本的宽度?

这是一个演示:

http://codepen.io/Tiger0915/pen/LEyePy

这是 SVG 标记:

<span>I want </span>

<svg width="100%" height="80px">
  <text x="0" y="0" fill="white">
    THESE WORDS
  </text>
</svg>

<span>to be an SVG</span>

理想情况下,我希望将 SVG 视为内联元素(例如 span 节点)。

我希望它像这样呈现:

I want THESE WORDS to be an SVG

其中 THESE WORDS 是 SVG。

如果我在 svg 节点上执行 width="auto" height="auto",它根本不会呈现。

如何使 SVG 元素自动适应其中文本元素的宽度?

我不知道有任何 SVG+CSS 解决方案。

您可以使用一些 JavaScript 来调整大小:

// get the bounding box for the text element
var bbox = text.getBBox();

// set the svg width/height accordingly
svg.setAttribute( 'width', bbox.width );
svg.setAttribute( 'height', bbox.height );

// set the viewbox accordingly
svg.setAttribute( 'viewBox', bbox.x + ' ' + bbox.y + ' ' + bbox.width + ' ' + bbox.height );

Modified Codepen

您的一般问题是,SVG 元素没有像其他图像那样的尺寸。您的 canvas 是(理论上)无限大小。 因此,为了确定大小,浏览器必须使用所有包含的元素,渲染它们,获取渲染坐标并计算最大边界框。 Afaik 没有浏览器这样做。