有没有一种方法可以使用CSS在SVG中填充图像?

时间:2018-11-20 15:07:37

标签: html css svg

就像填充一样的CSS样式,通过CSS设置笔触一样,有没有办法仅使用CSS将图像(背景图像)设置为SVG元素? 一些现有的解决方案在<image>元素中具有<svg>标记,但是由于使用了生成SVG的第三方库,因此我不想拥有该标记,因此CSS似乎是一个很好的选择替代。

更新: 我想将background添加到特定的svg元素,而不是整个SVG。没意识到早先在实际问题中没有提到它。

2 个答案:

答案 0 :(得分:1)

我认为您可以做的唯一方法是在单独的SVG中定义图案。然后,您可以通过CSS分配这些预定义的模式。

演示:

.filled {
  fill: url(#image-fill);
}
<svg width="0" height="0">

  <!-- image fills defined here in this hidden SVG -->
  <defs>
    <pattern id="image-fill"
             patternContentUnits="objectBoundingBox" width="1" height="1">
      <image x="0" y="0" width="1" height="1" preserveAspectRatio="xMidYMid slice"
             xlink:href="https://placekitten.com/400/400"/>
    </pattern>
  </defs>

</svg>



<svg viewBox="0 0 500 500">
  <path class="filled" d="M 100,50 L 450,200 L 150,350 Z" stroke="grey"/>
</svg>

答案 1 :(得分:0)

只需通过CSS添加即可。运行该代码片段以查看其工作原理:

svg{
  background: url("https://www.fillmurray.com/79/79");
}
<svg width="400" height="160" viewBox="0 0 400 160">
  <circle cx="200" cy="80" r="30" fill="red" stroke="white" stroke-width="4"></circle>
</svg>

相关问题