SVG - 带有背景颜色和圆形边框的文本 [英] SVG - Text with background color and rounded borders

查看:45
本文介绍了SVG - 带有背景颜色和圆形边框的文本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有可能用纯 SVG 做这样的事情?

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

没有 Javascript、固定大小或 html.

Without Javascript, fixed sizes or html.

我尝试使用 rect 元素,但这不是一个灵活的解决方案.

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.

推荐答案

您可以通过两种替代方式使用过滤器来做到这一点:

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

  1. 做一个洪水,模糊它,然后剪掉低不透明度,然后将剩余的不透明度调到最大
  2. 通过feImage走私圆角矩形并使用相对大小来拉伸它

在这两种情况下,填充都是相对的,因此如果您的文本太长,圆角将溢出过滤器区域.与 CSS 不同,您不能在 SVG 中组合相对和绝对大小(至少 SVG 1.1).所以这和你得到的一样好.

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.

由于您确实在寻找 HTML 文本行为,但又希望在 SVG 中使用它,因此您可能需要考虑使用 foreignObject 并以这种方式嵌入 HTML 文本.

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>

这篇关于SVG - 带有背景颜色和圆形边框的文本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆