Search code examples
htmlsvgviewbox

Keep svg pattern scaling when resizing svg-shape


I have a svg-pattern applied to a polygon. It's working fine. When I set another size on the svg-polygon, I don't want to scale the pattern.

I've tried all combinations I can think of with viewBox, patternUnits and patternContentUnits. The goal is to make the polygon work responsibly e.g. scale with it's parent element. Can anyone point me in the right direction?

<svg width="1000" fill="#ccc" viewBox="0 0 1440 60">
  <defs>
    <pattern id="pattern" x="0" y="0" width="900" height="600" patternUnits="userSpaceOnUse" patternContentUnits="userSpaceOnUse">
      <svg x="0" y="0" width="900.4" height="600" viewBox="0 0 900.4 600">
      <!-- pattern code -->
      </svg>
    </pattern>
  </defs>

  <polygon points="0,0 1440,0 1440,20 0,60" x="0" y="0" stroke="#bbb" fill="url(#pattern)" />
</svg>

<svg width="500" fill="#ccc" viewBox="0 0 1440 60">
  <defs>
    <pattern id="pattern" x="0" y="0" width="900" height="600" patternUnits="userSpaceOnUse" patternContentUnits="userSpaceOnUse">
      <svg x="0" y="0" width="900.4" height="600" viewBox="0 0 900.4 600">
      <!-- pattern code -->
      </svg>
    </pattern>
  </defs>

  <polygon points="0,0 1440,0 1440,20 0,60" x="0" y="0" stroke="#bbb" fill="url(#pattern)" />
</svg>

full example: https://codepen.io/anderssonola/pen/QqxKjJ


Solution

  • I solved temporarily by applying the pattern to a <rect>and then use css clip-pathto create the polygon and the pattern does not scale. I still would prefer to solve it with pure svg, since IE does not support the css clip-path.

    .clip {
      background: gray;
      clip-path: polygon(0 0, 100% 0, 100% 30%, 0% 100%);
      margin-bottom: 1em; 
    }
    
    .clip.half {
      width: 50%;
    }
    
    svg {
      display: block;
      height: 50px;
      width: 100%
    }
    <div > 
      <svg>
        <defs>
          <pattern id="pattern" x="0" y="0" width="900" height="600" patternUnits="userSpaceOnUse" patternContentUnits="userSpaceOnUse">
            <svg x="0" y="0" width="900.4" height="600"  >
            <!-- pattern code -->
            </svg>
          </pattern>
          <rect width="100%" height="50" fill="url(#pattern)" id="pattern-md"/>
        </defs>
      </svg>
    </div>
    
    <div class="clip">
      <svg>
         <use href="#pattern-md"/>
      </svg>
    </div>
    
    <div class="clip half" >
      <svg>
         <use href="#pattern-md" />
      </svg>
    </div>

    Working example: https://codepen.io/anderssonola/pen/oGyBMj/