SVG - Text with background color and rounded borders

让人想犯罪 __ 提交于 2021-02-10 14:21:03

问题


Is it possible to make such a thing with pure SVG?

Without Javascript, fixed sizes or html.

I tried to use a rect element but this is not a flexible solution.

I tried to use a filter but this is a solution without rounded corners.


回答1:


You can do this with a filter in two alternative ways:

  1. Do a flood, blur it, then clip the low opacities, then dial up the remaining opacity to full
  2. Smuggle in a rounded corner rect via feImage and use relative sizing to stretch it

In both cases padding is relative so if your text is too long, the rounded corners will overflow the filter area. Unlike CSS, you can't combine relative and absolute sizings in SVG (well SVG 1.1 at least). So this is as good as you get.

Since you're really looking for HTML text behavior but you want it in SVG, you might want to consider using a foreignObject and embedding HTML text that way.

<svg width="800px" height="600px">
<defs>
  <filter id="rounded-corners" x="-5%" width="110%" y="0%" height="100%">
<feFlood flood-color="#FFAA55"/>
<feGaussianBlur stdDeviation="2"/>
<feComponentTransfer>
  <feFuncA type="table"tableValues="0 0 0 1"/>
</feComponentTransfer>

<feComponentTransfer>
  <feFuncA type="table"tableValues="0 1 1 1 1 1 1 1"/>
</feComponentTransfer>
   <feComposite operator="over" in="SourceGraphic"/>
  </filter>
  
   <filter id="rounded-corners-2" primitiveUnits="objectBoundingBox">
<feImage preserveAspectRatio="none" width="110%" height="110%" x="-5%" y="0%"  xlink:href="data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' x='0px' y='0px' viewBox='0 0 400 40' height='40' width='400'%3E%3Crect fill='red' x='0' y='0' rx='10' ry='10' width='400' height='40'/%3E%3C/svg%3E"/>
   <feComposite operator="over" in="SourceGraphic"/>
  </filter> 
  
  
  </defs>

  
  <text filter="url(#rounded-corners)" x="20" y="40" style="font-size:30">Blur & opacity filter</text>
  
  <text filter="url(#rounded-corners)" x="20" y="80" style="font-size:30"> But the x padding is relative and overflows with long text</text>
  
<text filter="url(#rounded-corners-2)" x="20" y="140" style="font-size:30">feImage and a rect filter</text>
  
<text filter="url(#rounded-corners-2)" x="20" y="180" style="font-size:30">But you still can't get away from relative padding</text>

</svg>


来源:https://stackoverflow.com/questions/56172331/svg-text-with-background-color-and-rounded-borders

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!