Search code examples
svgsvg-filters

How to apply SVG filter(s) to create a colored SVG form of the whole silhouette?


I have an image in pgn, e.g. chess piece (white king)

Image of white King

Is there a simple way of applying SVG filters with this image to obtain an SVG containing the same shape (sillhouette( outline) and being filled with one color (e.g. red)?


Solution

  • In the case where your image has a white fill and a transparent outside, then yes, you can do this with an SVG filter.

    img {
      filter: url(#colorise);
    }
    <svg width="0" height="0" style="position: absolute">
      <defs>
        <filter id="colorise">
          <!-- Fill the filter area with red -->
          <feFlood flood-color="red" result="colour"/>
          <!-- Trim the red to just what's "in" (inside) the image (ie non-transparent) -->
          <feComposite operator="in" in="colour" in2="SourceGraphic"/>
          <!-- Multiply the trimmed red shape with the original image. Black parts stay black. White parts become red. -->
          <feBlend mode="multiply" in2="SourceGraphic"/>
        </filter>
      </defs>
    </svg>
    
    <img src="https://cdn.jsdelivr.net/gh/oakmac/chessboardjs/website/img/chesspieces/wikipedia/wK.png"/>

    Update

    How to make the whole thing red, including the black parts.

    img {
      filter: url(#colorise);
    }
    <svg width="0" height="0" style="position: absolute">
      <defs>
        <filter id="colorise">
          <!-- Fill the filter area with red -->
          <feFlood flood-color="red" result="colour"/>
          <!-- Trim the red to just what's "in" (inside) the image (ie non-transparent) -->
          <feComposite operator="in" in="colour" in2="SourceAlpha"/>
        </filter>
      </defs>
    </svg>
    
    <img src="https://cdn.jsdelivr.net/gh/oakmac/chessboardjs/website/img/chesspieces/wikipedia/wK.png"/>