缩放SVG形状以适应内容,其中内容包括foreignObject



有没有一种方法(最好不使用JavaScript)可以使用foreignObject将一些HTML内容放入SVG形状中,这样SVG形状就会自动调整大小(或缩放)以适应其内容?

也就是说,一些非常模糊的类似于这个伪代码示例的东西,但有效,并且以我所描述的方式起作用:

<?xml version="1.0" standalone="yes"?>
<svg xmlns = "http://www.w3.org/2000/svg">
  <rect x="10" y="10" width="SCALE_TO_FIT_CONTENTS" height="SCALE_TO_FIT_CONTENTS" fill="gray">
    <foreignobject width="100%" height="100%">
      <body xmlns="http://www.w3.org/1999/xhtml">
        <div>Some HTML text</div>
      </body>
    </foreignobject>
  </rect>
</svg>

如果不使用javascript,就不可能做到这一点。实际上,SVG形状不能用作容器。但是,我希望这就是你所要求的:

<script type="text/javascript">
    function myFun(){
        var w = document.getElementById("myDiv").scrollWidth;
        document.getElementById("myRect").setAttribute("width",w);
    }
</script>
<svg xmlns = "http://www.w3.org/2000/svg" onload="myFun()">
    <rect id="myRect" x="10" y="10" width="0" height="100" fill="red"></rect>
        <foreignObject x="10" y="10" position="absolute" width="100%" height="100%">
            <div id="myDiv" style="display: inline-block;">Some HTML text that resizes its SVG container</div>
        </foreignObject>
</svg>

一个不错的技巧是将所有内容都封装在<g>元素中,然后使用getBBox()测量该元素,然后内部内容的高度就已知了,并且可以用于修改父级SVG元素的高度。

var svg = document.querySelector('svg');
var bbox = svg.firstElementChild.getBBox();
svg.setAttribute("height", bbox.height + "px");
<svg>
  <g>
    <rect x="10" y="10" width="100" height="200px" fill="red"></rect>
        <foreignObject x="10" y="500" position="absolute" width="100%" height="100%">
            <div id="myDiv" style="display: inline-block;">Some HTML text that resizes its SVG container</div>
        </foreignObject>
        <text dy='500'>aaaaaaaaa</text>
  </g>
</svg>

最新更新