如何用图像填充多边形



我尝试使用模式将图像放入多边形中,但它不起作用。有什么办法可以填补这个吗?

<svg tabindex="1" style="width: 175px; height: 216.506px;">
  <polygon points="25,0 75,0 100,43 75,86 25,86 0,43" class="hexfield" tabindex="1" hex-row="0" hex-column="0"></polygon>
  <polygon points="100,44 150,44 175,87 150,130 100,130 75,87" class="hexfield" tabindex="1" hex-row="0" hex-column="1"></polygon>
  <polygon points="25,87 75,87 100,130 75,173 25,173 0,130" class="hexfield" tabindex="1" hex-row="1" hex-column="0"></polygon>
  <polygon points="100,130 150,130 175,173 150,216 100,216 75,173" class="hexfield" tabindex="1" hex-row="1" hex-column="1"></polygon>
  <defs>
    <pattern id="image1" x="0%" y="0%" height="100%" width="100%" viewBox="0 0 64 64">
      <image x="0%" y="0%" width="64" height="64" xlink:href="https://cdn4.iconfinder.com/data/icons/imod/512/Software/labo.png"></image>
    </pattern>
  </defs>
  
  <use xlink:href=".hexfield" fill="yellow"/>
  <use xlink:href=".hexfield" fill="url(#image1)"/>
</svg>

首先,请注意 xlink:href 已被弃用。

其次,xlink:href不使用CSS语法(其中# means ID. means class(。

因此,要引用一组 SVG,您应该xlink:href指向标记<g>的 id 。但是,如果您希望只有一个 SVG 获取定义,请将 xlink:href 指向 SVG id(不是类(:

<svg tabindex="1" style="width: 175px; height: 216.506px;">
<g id="hexfield">
  <polygon points="25,0 75,0 100,43 75,86 25,86 0,43"/>
  <polygon points="100,44 150,44 175,87 150,130 100,130 75,87"/>
  <polygon points="25,87 75,87 100,130 75,173 25,173 0,130" id="another"/>
  <polygon points="100,130 150,130 175,173 150,216 100,216 75,173"/>
</g>
  <defs>
    <pattern id="image1" height="100%" width="100%" viewBox="0 0 64 64">
      <image width="64" height="64" xlink:href="https://cdn4.iconfinder.com/data/icons/imod/512/Software/labo.png"/>
    </pattern>
    <pattern id="image2" height="100%" width="100%" viewBox="0 0 64 64">
      <image width="64" height="64" xlink:href="https://cdn4.iconfinder.com/data/icons/imod/512/Software/iPhoto.png"/>
    </pattern>
  </defs>
  
  <use xlink:href="#hexfield" fill="yellow"/>
  <use xlink:href="#hexfield" fill="url(#image1)"/>
  <use xlink:href="#another" fill="red"/>
  <use xlink:href="#another" fill="url(#image2)"/>
</svg>

最新更新