从反色文字到mix-blend-mode

最近有一个需求,意思大概是这样:

也就是将字体颜色设置为背景色的反色。

搜索了一下,决定使用css3提供的新属性:mix-blend-mode(混合模式)

用过ps的都应该理解混合模式是一个强大的图层调色功能,和大神对各种混合特效的信手拈来不同,我对这个功能的理解非常短浅,所以也只是初步了解一下这个功能。

一、实现反色文字

首先解决一下开头的问题:

1
2
3
<div class="background">
<div class="text">反色文字</div>
</div>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
.background {
position: relative;
width: 400px;
height: 150px;
background: linear-gradient(90deg, #f00, #ff0, #0f0, #0ff, #00f, #f0f);
}
.text {
position: absolute;
left: 0;
top: 0;
font-size: 100px;
mix-blend-mode: difference; /* 由于字体色是纯色,这里也可以使用exclusion */
text-shadow: 1px 1px 0 #000;
color: white; /* 配合白色底色实现与背景颜色值相反 */
}

取字体色和背景色三通道的差的绝对值作为结果,也就是:

最终通道值 = | 对应字体色通道值 - 对应背景色通道值 |

(mix-blend-mode: difference;原理)

二、mix-blend-mode属性值

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
div {
mix-blend-mode: normal; /* 正常 */
mix-blend-mode: multiply; /* 正片叠底 */
mix-blend-mode: screen; /* 滤色 */
mix-blend-mode: overlay; /* 叠加 */
mix-blend-mode: darken; /* 变暗 */
mix-blend-mode: lighten; /* 变亮 */
mix-blend-mode: color-dodge; /* 颜色减淡 */
mix-blend-mode: color-burn; /* 颜色加深 */
mix-blend-mode: hard-light; /* 强光 */
mix-blend-mode: soft-light; /* 柔光 */
mix-blend-mode: difference; /* 差值 */
mix-blend-mode: exclusion; /* 排除 */
mix-blend-mode: hue; /* 色相 */
mix-blend-mode: saturation; /* 饱和度 */
mix-blend-mode: color; /* 颜色 */
mix-blend-mode: luminosity; /* 亮度 */

mix-blend-mode: initial; /* 初始 */
mix-blend-mode: inherit; /* 继承 */
mix-blend-mode: unset; /* 复原 */
}

至于他们能生成什么奇妙的效果呢,可以去参观一下这个大佬的作品:https://www.cnblogs.com/coco1s/p/6829372.html