如何使用CSS将白色透明图像重新着色为任意颜色? [英] How to recolor a white-on-transparent image to an arbitrary color using CSS?
问题描述
How do I take a image with just white and transparent pixels (example) and recolor to, say, red or orange, using only CSS?
以下问题是先前提出的-
Question below was asked previously -
答案说要使用过滤器,但没有指出什么组合的过滤器才能使它起作用.是否有任何滤镜组合可以使我将透明白色图像更改为红色图像?
The answer says to use filters, but does not indicate what combination of filters would make it work. Are there any filter combinations that would allow me to change a white-on-transparent image to red?
为了澄清:我想为图像的白色部分重新着色,而不是为背景着色.例如,我希望它是透明的.
To clarify: I would like to recolor the white portion of the image, not color the background. For example, I would like it red-on-transparent.
img {
-webkit-filter: brightness(50%) saturate(200%) hue-rotate(90deg);
}
<img src="https://upload.wikimedia.org/wikipedia/commons/thumb/f/f4/White_Globe_Icon.png/600px-White_Globe_Icon.png"></img>
推荐答案
我试了一下,发现了一种可能的解决方案,只涂白色部分:
I played around a bit and found a possible solution to only paint the white parts:
img {
display: block;
background: black;
-webkit-filter: brightness(.5);
}
.recolor {
position: relative;
display: inline-block;
-webkit-filter: brightness(1) contrast(300%) invert(1);
}
.recolor:after {
content: "";
display: block;
position: absolute;
top: 0;
bottom: 0;
left: 0;
right: 0;
background: rgba(0, 255, 255, 0.3);
}
<figure class="recolor">
<img src="https://upload.wikimedia.org/wikipedia/commons/thumb/f/f4/White_Globe_Icon.png/200px-White_Globe_Icon.png">
</figure>
工作原理:
- 将图像背景设为黑色,并将其亮度设置为一半,以使前景变为灰色
- 创建一个包装元素(
< figure>
)并创建您希望的反转颜色的叠加层(:after
),并且具有相对较低的不透明度 - 现在过滤包装器元素:以高对比度使它如此明亮,以至于背景变为黑色,但前景颜色仍然保留.
- 现在只需反转包装器,使您的前景色变为白色
- Make image background black and set its brightness to a half, to make the foreground gray
- Create a wrapper element (
<figure>
) and create an overlay (:after
) of the inverted color you wish with a relatively low opacity - Now filter the wrapper element: make it so bright with such high contrast, that the background becomes black, but the foreground color remains.
- Now just invert the wrapper to get your foreground color on white
限制:透明度丢失,因为过滤颜色可能不完全是您想要的颜色,浏览器支持不是最佳
Limits: Transparency gets lost, due to filtering the colors are maybe not exactly the colors you want, browser support is not optimal
这篇关于如何使用CSS将白色透明图像重新着色为任意颜色?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!