absolute
absolute

Reputation: 47

Include a png/svg inside a polygon?

I'm trying to think of the best way to include an image inside an SVG polygon element, like the below:

<svg id="graph" width="100%" height="400px">
  <!-- pattern -->
  <defs>
    <pattern id="image" 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>
  <polygon stroke="red" stroke-width="2px" fill="url(#image)" points="300,150 225,280 75,280 0,150 75,20 225,20"></polygon>
</svg>

However, i also want to fill the polygon with a background colour fill, but as this is using the above pattern i'm not sure of the right approach.

Upvotes: 3

Views: 1148

Answers (1)

Andrew Willems
Andrew Willems

Reputation: 12458

Move your polygon into your defs, but take the fill out. Then make two copies with the use tag, the back one filled with your color and the front one filled with your image. You can also make multiple copies by including more images, changing the coordinates, etc.

<svg id="graph" width="100%" height="400px">
  <!-- pattern -->
  <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>
    <pattern id="image2" 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/iPhoto.png"></image>
    </pattern>
    <polygon id="myShape" stroke="red" stroke-width="2px" points="300,150 225,280 75,280 0,150 75,20 225,20"></polygon>
  </defs>
  <use xlink:href="#myShape" fill="yellow"/>
  <use xlink:href="#myShape" fill="url(#image1)"/>
  <use xlink:href="#myShape" fill="orange" x="400"/>
  <use xlink:href="#myShape" fill="url(#image2)" x="400"/>
</svg>

Upvotes: 3

Related Questions