圆形内的SVG图像

15

我想创建一个包含图像的圆形,我已经尝试使用patternfilter,但没有一个能给我期望的结果。以下是代码:

<svg id="graph" width="100%" height="400px">

  <!-- filter -->
  <filter id = "born1" x = "0%" y = "0%" width = "100%" height = "100%">
      <feImage xlink:href = "https://cdn3.iconfinder.com/data/icons/people-professions/512/Baby-512.png"/>
  </filter>
  <circle id = "born" class = "medium" cx = "5%" cy = "20%" r = "5%" fill = "white" stroke = "lightblue" stroke-width = "0.5%" filter = "url(#born1)"/>
  
  <!-- pattern -->
  <defs>
    <pattern id="image" x="0" y="0"  height="100%" width="100%">
      <image x="0" y="0" xlink:href="https://cdn3.iconfinder.com/data/icons/people-professions/512/Baby-512.png"></image>
    </pattern>
  </defs>
  <circle id = "sd" class = "medium" cx = "5%" cy = "40%" r = "5%" fill = "white" stroke = "lightblue" stroke-width = "0.5%" fill="url(#image)"/>
</svg>

我的目标是保留圆形,将背景图像放在圆形内,类似于CSS属性background-image

3个回答

33

一个模式会起作用。您只需为<image>指定大小即可。与HTML不同,SVG图像默认宽度和高度为零。

另外,如果你想让图片随着圆形缩放,那么你应该为模式指定一个viewBox

<svg id="graph" width="100%" height="400px">

  <!-- pattern -->
  <defs>
    <pattern id="image" x="0%" y="0%" height="100%" width="100%"
             viewBox="0 0 512 512">
      <image x="0%" y="0%" width="512" height="512" xlink:href="https://cdn3.iconfinder.com/data/icons/people-professions/512/Baby-512.png"></image>
    </pattern>
  </defs>
    
  <circle id="sd" class="medium" cx="5%" cy="40%" r="5%" fill="url(#image)" stroke="lightblue" stroke-width="0.5%" />
</svg>


3

这是一种替代SVG的方法,实际上并不需要使用SVG。你可以通过图片标签本身来实现你的目标。

.avatar {
    vertical-align: middle;
    width: 20px;
    height: 20px;
    border-radius: 50%;
    border: solid 5px red;
}

<img src="https://connectoricons-prod.azureedge.net/kusto/icon_1.0.1027.1210.png" alt="Avatar" class="avatar">

Refer here for live demo


我已经在答案中清楚地提到了。这是SVG的替代方案。请查看实时演示链接。 - SRIDHARAN
1
如果有人问你“如何修理宝马的发动机”,你会建议他买一辆大众汽车吗? - xoned
哈哈,那不是我的意图。这是一个更好的选择。我正在寻找与问题要求相同的期望输出。我发现这个答案很有用。 - SRIDHARAN
1
问题并没有提到SVG;它要求“创建一个包含图像的圆形”。这比SVG更好。 - Dan

2
尝试这个, 使用patternUnits="userSpaceOnUse"并设置<image>height="100%" width="100%"
 <defs>
    <pattern id="image" x="0" patternUnits="userSpaceOnUse" y="0" height="100%" width="100%">
      <image x="0" y="0" width="500" height="500" xlink:href="http://www.viralnovelty.net/wp-content/uploads/2014/07/121.jpg"></image>
    </pattern>
  </defs>

Demo


1
将您的图像网址更改为我的,使其无法正常工作。有什么想法吗? - Bla...

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接