Reputation: 2848
Let's say I have an image that contains only red and transparent pixels:
Now I want the red pixels to show up as any color I choose. Is this possible with something like -webkit-filter
? I already know how to assign it an arbitrary hue (hue-rotate(Ndeg)
) and how to make it darker (brightness(N%)
), but making it lighter (i.e. pink) eludes me. brightness(200%)
has no apparent effect. I've also tried starting from a white image, but I can't seem to saturate it.
If there is a JavaScript library that converts any hex color to a series of CSS filters (or anything else that accomplishes this task), that would be optimal, but I doubt such a library exists. I might write one myself if I can figure it out.
Upvotes: 0
Views: 170
Reputation:
You can use a canvas to change the color:
For example - just dry isolated code but adjust as needed:
/// draw image onto canvas of same size as image
ctx.drawImage(img, 0, 0);
/// KEY: change composite mode
ctx.globalCompositeOperation = 'source-in';
/// pick any color you want
ctx.fillStyle = '#00f';
/// draw rectangle on top with fill style - only solid pixels will change
ctx.fillRect(0, 0, canvas.width, canvas.height);
The composite mode used here will make sure only solid colors are filled; the transparent pixels will remain transparent. You could fill with anything really, gradient, another image and so on.
After this is complete you can now either use the on-screen canvas as-is (it will show as an image) or you can get a data-uri from the canvas which you can set as source for another image element by using 'canvas.toDataURL()` however for this last to work you need to fulfill CORS requirement. The simplest is to use the canvas directly.
Upvotes: 1
Reputation: 2213
Have you tried the opacity
filter? Although not exactly what you may want (i.e. a lightness filter), the following gives me pink in the above situation:
img {
-webkit-filter: opacity(30%);
}
See the following: http://codepen.io/micjamking/pen/222c540689d92ec1df1a3b6e1ea2933f
Upvotes: 0