Search code examples
csssvg

Combine clipPath, pattern, and linearGradient in SVG


I am trying to create a background that consists of multiple dots gradienting from say green to yellow from left to right. So the idea was to create a path, fill it with a gradient and clip path with a pattern:

https://codepen.io/Deka87/pen/pLPqJE?editors=1000

<svg width='100' height='100' viewBox="0 0 100 100" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink">
  <defs>
    <linearGradient id="img-dotted-gradient">
      <stop offset="0%" stop-color="green"></stop>
      <stop offset="100%" stop-color="yellow"></stop>
    </linearGradient>
    <pattern id="img-dotted-dots" x="0" y="0" width=".1" height=".1">
      <circle cx="2" cy="2" r="2" fill="green"></circle>
    </pattern>
  </defs>
  <path d="M0 0 H 100 V 100 H 0 Z" fill="url(#img-dotted-gradient)" clip-path="url(#img-dotted-dots)"></path>
</svg>

The gradient works OK, the clip path works OK (standalone). However they don't come together.


Solution

  • Only the shape of the elements in a <clipPath> matter. The colour and fill are ignored, so you can't do it that way.

    But you can use a <mask> instead.

    <svg width='100' height='100' viewBox="0 0 100 100" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink">
      <defs>
        <linearGradient id="img-dotted-gradient">
          <stop offset="0%" stop-color="green"></stop>
          <stop offset="100%" stop-color="yellow"></stop>
        </linearGradient>
        <pattern id="img-dotted-dots" x="0" y="0" width=".1" height=".1">
          <circle cx="2" cy="2" r="2" fill="white"></circle>
        </pattern>
        <mask id="img-dotted-mask">
          <rect width="100" height="100" fill="url(#img-dotted-dots)"/>
        </mask>
      </defs>
      <path d="M0 0 H 100 V 100 H 0 Z" fill="url(#img-dotted-gradient)" mask="url(#img-dotted-mask)"></path>
    </svg>