3

I have an image that has:

  • White pixels: I would like to dynamically set these to any colour
  • Black pixels: I would like these to remain black
  • Transparent pixels: I would like these to show through whatever background it is currently on.

Here is an example of the image overlaid on a reddish background:

bunny

I would like to be able to tint the bunny any colour I like, without resorting to background tricks because the background colour that the tinted image is shown against, should show through unchanged.

A pure CSS solution is preferred, but javascript image manipulation ideas are also welcome.

The bunny by itself:

bunny by itself

CSJ
  • 3,641
  • 2
  • 19
  • 29
  • There is no HTML or CSS way to manipulate images. Espacially there is no way to detect the color of an image. The only possible way to solve this is, if the image itself is a SVG directly inside the HTML markup. – tacoshy Mar 15 '22 at 02:18
  • share the transparent image without the reddish background – Temani Afif Mar 15 '22 at 20:20
  • There is a very detailed [answer](https://stackoverflow.com/a/43960991/10046781) made with JS. It converts from black to any desired color. But be aware the conversion is not 100% accurate – David Alberici Mar 15 '22 at 21:39

1 Answers1

2

Using mask and blend mode you can do it:

.bunny {
  --img: url(https://i.ibb.co/ngFGkgy/clOwR.png); /* Your png */

  width: 32px;
  aspect-ratio: 1;
  background: var(--img) center/cover;
  background-blend-mode: darken;
  -webkit-mask: var(--img) center/cover;
          mask: var(--img) center/cover;
          
  background-color: red; /* the color */
}
<div class="bunny"></div>
<div class="bunny" style="width:100px;background-color:green"></div>
<div class="bunny" style="width:100px;background-color:blue"></div>
Temani Afif
  • 245,468
  • 26
  • 309
  • 415
  • Could you explain a bit more why does it work? Maybe a high level explanation of what mask and blend do – David Alberici Mar 15 '22 at 21:42
  • It's perfect. (I tried it with a yellow background just to make sure) – CSJ Mar 15 '22 at 22:10
  • 2
    @DavidAlberici using mask will only show the non-transparent part of the image (the whole bunny) then I use the same bunny as background-image and behind it a background-color. Since we have a white/black color for the bunny using `darken` will always show the darkest color so the black and what you have as background-color – Temani Afif Mar 15 '22 at 22:24