【问题标题】:SVG: dynamic size based on text, merging objectsSVG:基于文本的动态大小,合并对象
【发布时间】:2012-12-01 10:58:06
【问题描述】:
<div style="float: left; padding: 10px; border: 1px solid; 
background: #ccc">random text</div>

有没有办法在 SVG 中实现这样的功能?我的意思是有一个矩形和一个文本:

a) 矩形的宽度和高度是动态的,所以当我更改文本时,矩形会调整其大小
b)当我移动矩形时,文本随之而来

&lt;canvas&gt; 中实现这样的目标会更容易吗?

编辑:

<defs>       
    <text id="text1" x="90" y="100" style="text-anchor:start;font-size:30px;">
    THIS IS MY HEADER</text>
</defs>

<filter x="0" y="0" width="1" height="1" id="background">
    <feFlood flood-color="gray"/>
    <feComposite in="SourceGraphic"/>
</filter>

<use xlink:href="#text1" fill="black" filter="url(#background)"/>

Erik Dahlström 提出了类似的建议。如何将填充放在背景中,如何添加例如。矩形的阴影或边框?而且,这在 IE9 中不起作用,所以我不能接受。如果 IE 支持它,我可以使用 &lt;foreignObject&gt;

我刚刚找到了我的问题中 b) 点的答案。您必须将两个元素都放在组中:

<g>
    <rect x="0" y="0" width="100" height="100" fill="red"></rect>
    <text x="50" y="50" font-size="14" fill="blue" text-anchor="middle">Hello</text>
</g>

然后您可以使用transform 参数移动组:

<g transform="translate(x, y)">

似乎在每个浏览器中都能正常工作。

【问题讨论】:

  • IE9 不支持过滤器或foreignObject。 IE10 支持过滤器,但不支持 foreignObject (AFAIK)。

标签: svg


【解决方案1】:

您可以使用 JavaScript 来调整框:

<svg xmlns="http:/www.w3.org/2000/svg" onload="init()" height="100" width="200">
      <style type="text/css">
        rect {
          stroke:black;
          stroke-width:1;
          fill:#ccc;
        }
      </style>
      <script type="text/javascript">
        var text, rect
        var padding = 10
        function init() {
          text = document.getElementsByTagName("text")[0]
          rect = document.getElementsByTagName("rect")[0]
          adjustRect()
        }
        
        function adjustRect() {
          var bbox = text.getBBox()
          rect.setAttribute("x",bbox.x - padding)
          rect.setAttribute("y",bbox.y - padding )
          rect.setAttribute("width",bbox.width + 2*padding)
          rect.setAttribute("height",bbox.height + 2*padding)
        }
        
      </script>
      <g>
        <rect x="0" y="0" width="100" height="100" fill="red"></rect>
        <text x="50" y="50" font-size="14" fill="blue" text-anchor="middle">Hello</text>
      </g>
    </svg>
    <div>
      <button onclick="text.textContent='Goodbye';adjustRect()">change text</button>
    </div>

【讨论】:

    【解决方案2】:

    使用 svg 过滤器绘制背景,这将适应文本的大小和位置。有关完整示例,请参阅 this answer

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2010-09-21
      • 1970-01-01
      • 2014-10-21
      • 2012-10-24
      • 1970-01-01
      • 2014-08-09
      • 1970-01-01
      • 2021-07-02
      相关资源
      最近更新 更多