user3242861 user3242861 - 2 months ago 6
CSS Question

SVG - Fill polygon with image and map

I'm trying to put an image in svg polygon shape but this doesn't work well.

I don't understand why the image doesn't fill all the SVG shape.

Can anyone help me? I also need that to put a google maps image instead, how can I do that?

My code:



#services
{
position: relative;
width: 100%;
height: 600px;
}

#services .services-shape
{
position: absolute;
width: 100%;
height: 500px;
}

#services .services-shape .svg-shape-top
{
width: 100%;
height: 100%;
position: absolute;
}

#services .services-shape .svg-shape-top svg
{
position: relative;
width: 100%;
height: 100%;
fill: transparent;
stroke: red;
}

<section id="services">
<div class="services-shape">
<div class="svg-shape-top">
<svg viewBox="0 0 100 100" preserveAspectRatio="none">
<defs>
<pattern id="imgpattern" x="0" y="0" width="1" height="1">
<image width="100%" height="100%"
xlink:href="https://a2ua.com/paisagem/paisagem-007.jpg"/>
</pattern>
</defs>
<path fill="url(#imgpattern)" d="M 50 0, 100 25, 100 100, 50 100, 0 100, 0 25Z" />
</svg>

</div>
</div>
</section>





Thank's

Answer

The image and the shape have different aspect ratios. By default the image's aspect ratio is preserved. The preserveAspectRatio attribute can override this as I've done below.

#services
{
  position: relative;
  width: 100%;
  height: 600px;
}

#services .services-shape
{
  position: absolute;
  width: 100%;
  height: 500px;
}

#services .services-shape .svg-shape-top
{
  width: 100%;
  height: 100%;
  position: absolute;
}

#services .services-shape .svg-shape-top svg
{
  position: relative;
  width: 100%;
  height: 100%;
  fill: transparent;
  stroke: red;
}
<section id="services">
  <div class="services-shape">
    <div class="svg-shape-top">
      <svg viewBox="0 0 100 100" preserveAspectRatio="none">
        <defs>
          <pattern id="imgpattern" x="0" y="0" width="1" height="1">
            <image width="100%" height="100%" preserveAspectRatio="none"
                   xlink:href="https://a2ua.com/paisagem/paisagem-007.jpg"/>
          </pattern>
        </defs>
        <path fill="url(#imgpattern)" d="M 50 0, 100 25, 100 100, 50 100, 0 100, 0 25Z" />
      </svg>

    </div>
  </div>
</section>

Comments