block by ee2dev 587ec9c20a8ac46e43be5032103d9934

Coloring a transparent image

Full Screen

How to color a raster black and white image with a transparent outside. Based on https://stackoverflow.com/questions/57650474/how-to-apply-svg-filters-to-create-a-colored-svg-form-of-the-whole-silhouette/57656454

Built with blockbuilder.org

index.html

<!DOCTYPE html>
<head>
  <meta charset="utf-8">
  <style>
    img.complete-red {
      filter: url(#colorise);
    }
    
    img.filled-red {
      filter: url(#colorise2);
    }
    body { margin:0;position:fixed;top:0;right:0;bottom:0;left:0; }
  </style>
</head>

<body>
  
  <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>
    <filter id="colorise2">
      <!-- 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" class="original"/>
  <img src="https://cdn.jsdelivr.net/gh/oakmac/chessboardjs/website/img/chesspieces/wikipedia/wK.png" class="filled-red"/>
<img src="https://cdn.jsdelivr.net/gh/oakmac/chessboardjs/website/img/chesspieces/wikipedia/wK.png" class="complete-red" width=90 height=90/>

</body>