我尝试通过使用图案将图像放置在多边形内,但不起作用。有什么办法可以解决这个问题吗?

<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 is deprecated

其次,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>

关于javascript - 如何用图像填充多边形?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/55669831/

10-11 14:28