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

sam*_*per 7 html xhtml svg

有没有办法 - 最好不使用JavaScript - 将一些HTML内容放入SVG形状中foreignObject,这样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>
Run Code Online (Sandbox Code Playgroud)

小智 5

如果不使用 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>
Run Code Online (Sandbox Code Playgroud)