为了理解为什么我们需要进行一些数学运算。
If we start with the invert(1)
(the easiest one) we will use f(x) = (255 - x)
ref https://stackoverflow.com/a/48798480/8620333. So
rgb(255,0,0)
will become rgb(0,255,255)
For the hue-rotate(180deg)
它更复杂。考虑到规格 https://drafts.fxtf.org/filter-effects/#feColorMatrixElement我们将得到以下矩阵:
-0.574 1.43 0.144
0.426 0.43 0.144
0.426 1.43 -0.856
所以我们会有
R' = -0.574*R 1.43*G 0.144*B = 1.43*255 + 0.144*255 = 401.37
G' = 0.426*R 0.43*G 0.144*B = 0.43*255 + 0.144*255 = 146.37
B' = 0.426*R 1.43*G -0.856*B = 1.43*255 - 0.856*255 = 146.37
然后是最终颜色rgb(255,146.37,146.37)
哪一个不是红色的
html {
background: rgb(255, 146.37, 146.37)
}
如何使用 CSS 反转图像并且仍然使红色看起来像红色?
这取决于考虑其他颜色您想要得到什么结果,但您可以添加staturate()
过滤器恢复红色:
img {
filter: invert(1) hue-rotate(180deg) saturate(10);
}
<img src="https://i.stack.imgur.com/jikdT.png">
再次一些数学来了解发生了什么。根据相同的规范,经过一些简化,我们将得到以下矩阵:
7.87 -7.15 -0.72
-2.13 2.85 -0.72
-2.13 -7.15 9.28
So
R' = 7.87*R -7.15*G -0.72*B = 7.87*255 - 7.87*146.37 = bigger than 255
G' = -2.13*R 2.85*G -0.72*B = -2.13*255 + 2.13*146.37 = negative
B' = -2.13*R -7.15*G 9.28*B = -2.13*255 + 2.13*146.37 = negative
最终颜色rgb(255,0,0)