根据内容调整 SVG 矩形宽度

Adjust SVG rect width according to its content

我正在创建一个包含几个矩形的 SVG 动态

矩形内有一个文本,其宽度可以改变。

我想根据文本的长度调整矩形的宽度。

有可能吗?有什么解决方法?

这里有一个 fiddle 和一个简单的例子:

Fiddle

这是 SVG:

  <div class="container">
   <svg height="180" width="500">
      <g transform="translate(100, 50)">
         <rect width="100%" class="node" rx="17" height="30" style="fill: rgb(255, 255, 255); cursor: default;"></rect>
         <circle cx="15" cy="15" r="15" fill="#FFFFFF" filter="url(#circleShadow)" stroke="lightgray" stroke-width="0.1" width="15" height="15"></circle>
         <text x="40" y="19" class="graph-element-text node-text-color" style="cursor: pointer;">long text11111111111111122222</text>
      </g>
   </svg>
</div>

正如@Robert Longson 所暗示的那样:您必须模仿 <div> 类似 svg 文本框的显示,因为 <text> 元素没有任何 auto-growing 功能。 (至少比不上 html 块元素)。

实际上,<rects> 不能换行文本元素(例如 div)

解决方法可能是使用 foreign object:

.container {
  background-color: lightgray;
}


.graph-background-color {
    background-color: #F8F8F9;
}

svg {
  fill: yellow;
  display:inline-block;
}


.text-wrp{
    text-align:center;
}
.inner-text{
  text-align:center;
  background:#fff;
  width:auto;
  display:inline-block;
  text-align:center;
  padding:0.5em 0.5em 0.5em 2em;
  height:30px;
  font-size:15px;
  line-height:1.75em;
  border-radius: 2em 0 0 2em
}
<div >
  <svg class="container" height="180" width="500">
    <g>
      <foreignObject x="50%" y="50%" width="50%" height="50" style="transform:translateX(-25%) translateY(-15%)">
        <div class="text-wrp" xmlns="http://www.w3.org/1999/xhtml">
          <div class="inner-text" xmlns="http://www.w3.org/1999/xhtml">
            long text11111111111111122222</div>
          </div>
      </foreignObject>
    </g>
  </svg>
</div>

<foreignObject> 可能会引入问题,当您的 svg 需要独立时(例如,也应该在 Ai、inkscape 等编辑器中可编辑)。