Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to change color of SVG pattern on usage?

I would like to change the color of pattern upon usage.

For example, I would like to have a green pattern in the red stroked circle.

<svg width="300" height="300" viewBox="0 0 300 300"
    xmlns="http://www.w3.org/2000/svg">
  <defs>
    <pattern id="checked" width="2" height="2" stroke="black" stroke-linecap="square" stroke-width="1" patternTransform="rotate(45) scale(2)"
        patternUnits="userSpaceOnUse">
      <line x1="0" y1="0" x2="0" y2="2"></line>
      <line x1="0" y1="0" x2="2" y2="0"></line>
    </pattern>
  </defs>
  <circle cx="60" cy="60" r="50" stroke="red" fill="url(#checked)"/>
  <circle cx="120" cy="60" r="50" stroke="blue" fill="url(#checked)"/>
</svg>

http://codepen.io/anon/pen/RVNmRY

Is it possible to do so without having to create a new pattern for every color?

I have read in a comment that this might be possible using filters (https://stackoverflow.com/a/21427316/1981832). But I don't know how.

like image 717
Daniel Avatar asked Apr 15 '17 07:04

Daniel


People also ask

Can SVGs be colored?

You're largely limited to a single color with icon fonts in a way that SVG isn't, but still, it is appealingly easy to change that single color with color . Using inline SVG allows you to set the fill , which cascades to all the elements within the SVG, or you can fill each element separately if needed.


1 Answers

It works if you fill the circles with the desired color and then apply the pattern as a mask. Here is an example for green and magenta:

<svg width="300" height="300" viewBox="0 0 300 300"
    xmlns="http://www.w3.org/2000/svg">
  <defs>  
    <pattern id="checked" width="2" height="2" stroke="white" stroke-linecap="square" stroke-width="1" patternTransform="rotate(45) scale(2)"
        patternUnits="userSpaceOnUse">
      <line x1="0" y1="0" x2="0" y2="2"></line>
      <line x1="0" y1="0" x2="2" y2="0"></line>
    </pattern>
    <mask id="checked-mask" x="0" y="0" width="1" height="1" >
      <rect x="0" y="0" width="1000" height="1000" fill="url(#checked)" />
    </mask>
  </defs>  
  <circle cx="60" cy="60" r="50" stroke="red" mask="url(#checked-mask)" fill="green" />
  <circle cx="120" cy="60" r="50" stroke="blue" mask="url(#checked-mask)" fill="magenta" />
</svg>
like image 172
Waruyama Avatar answered Sep 23 '22 17:09

Waruyama