Search code examples
csssvgtexturesmask

Assign a pattern to the whole page but reveal it only on some shapes, the rest should be black


I would like to create a web page where the background is flat black but I need to add also a background pattern that should be visible only inside some shapes (circles in this simple example, but they will be a complicated path, different for each section).

I know I could assign the pattern to the shapes, but I need also to animate the shapes and is not possible to animate the pattern.

Here my starting code

I applied a texture in CSS to the entire page and I add some circles. Now I need to "hide" the texture everywhere except inside the shapes. And the page background should be black. How can I do that?


Solution

  • Is this the sort of thing you are after?

    /* hide the SVG */
    svg#pattern {
      position: absolute;
      left: -9999px;
    }
    
    
    body {
      background-color: black;
      height: 2000px;
      color: white;
    }
    
    section {
      height: 400px;
    }
    
    circle {
      animation: throb 1s infinite;
    }
    
    @keyframes throb {
      0% { r: 48px; }
      50% { r: 30px; }
      100% { r: 48px; }
    }
    <svg id="pattern">
      <defs>
        <pattern id="check" width="10" height="10" patternUnits="userSpaceOnUse">
          <rect width="10" height="10" fill="linen"/>
          <rect width="5" height="5" fill="black"/>
          <rect x="5" y="5" width="5" height="5" fill="black"/>
        </pattern>
      </defs>
    </svg>
    
    
    <div>
      <h1>Test page</h1>
    
      <section>
        <svg width="400" height="100">
          <circle cx="50" cy="50" r="48" fill="url(#check)"/>
        </svg>
      </section>
    
      <section>
        <svg width="400" height="100">
          <circle cx="50" cy="50" r="48" fill="url(#check)"/>
        </svg>
      </section>
    
      <section>
        <svg width="400" height="100">
          <circle cx="50" cy="50" r="48" fill="url(#check)"/>
        </svg>
      </section>
          
    </div>