这几天正好看到一篇公众号几行代码实现了给头像加国旗的效果,用到了css3的mask属性,之前没怎么接触过这个属性,感觉还挺有趣的(?
当然我也没有玩出什么新花样,下面的特效基本都是网上能找到的,进行了一些小修改,顺便记录一下万一以后用得上🕶️
搭配高斯模糊背景
<body>
<div class="background"></div>
<div class="mask"></div>
</body>
body {
display: flex;
justify-content: center;
}
.background {
background: url(https://raw.githubusercontent.com/GEGE-csy/test/master/WeChat17289531665be5a0f0e4c79b34265ae0.png);
/* 背景图完全覆盖 */
background-size: cover;
/* 背景图固定定位,占满整个窗口 */
position: fixed;
top: 0;
left: 0;
width: 100%;
height: 100%;
/* 给图像设置高斯模糊 */
filter: blur(15px);
}
.mask {
width: 500px;
height: 500px;
/* mask要遮罩的背景图 */
background-image: url(https://raw.githubusercontent.com/GEGE-csy/test/master/WeChat17289531665be5a0f0e4c79b34265ae0.png);
background-size: cover;
/* 选择的mask遮罩图就是👆那张404图 */
-webkit-mask: url(https://raw.githubusercontent.com/GEGE-csy/test/master/404%E9%94%99%E8%AF%AF.png);
-webkit-mask-size: cover;
/* 这个动画我感觉不设也可 */
animation: move 20s infinite;
}
/* 改变mask遮罩的背景图的定位 */
@keyframes move {
0% {
background-position: 0 0;
}
50% {
background-position: 100% 0;
}
}
参考来源:https://juejin.cn/post/6844903695042215944
鼠标移哪显示哪
原谅我不知道这个叫啥😢
<!--选一张背景图 -->
<body>
<img id="img" src="https://raw.githubusercontent.com/GEGE-csy/test/master/WeChat17289531665be5a0f0e4c79b34265ae0.png">
</body>
img {
/* 背景图铺满屏幕 */
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
/* 选择的mask遮罩图就是一张圆形图片 */
-webkit-mask-image: url(https://raw.githubusercontent.com/GEGE-csy/test/master/WeChatbf24151aa6fcb12bf5bdfd5fceecb8ec.png);
/* no-repeat不要漏 不然满屏都是⭕️*/
-webkit-mask-repeat: no-repeat;
/* 调整一下圆形图的大小 */
-webkit-mask-size: 150px 150px;
}
window.onload = function() {
const img = document.getElementById('img');
img.onmouseover = function(e) {
isActive = true;
}
img.onmousemove = function(e) {
if(isActive) {
/* 用js来改变css中的mask的position值 */
/* 注意pageX和pageY要减去的是mask遮罩圆形图宽高的一半,这样你的光标才会出现在圆形图的中央 */
img.style.cssText = '-webkit-mask-position:' + (e.pageX-75) + 'px' + (e.pageY-75) + 'px;';
}
}
img.onmouseout = function(e) {
isActive = false;
}
}
参考来源:https://www.cnblogs.com/dtdxrk/p/4530063.html
多张图的融合
这就要用到linear-gradient()
函数了
传两种参数
- 角度值,指定渐变方向
这里不止可以填角度值,还可以填to right
、to bottom right
直接指定渐变方向 - 渐变的起止颜色
颜色值(必需)和位置值(选填),位置值可以用数值或者百分比来表示
例如#000 6px, transparent 6px
就是前6px都是#000色,6px之后都是transparent
mask配合linear-gradient()真的可以非常自然地融合多张图
拿前面提到过的国旗头像当例子
<body>
<div class="head"></div>
<div class="flag"></div>
</body>
div {
/* 通过定位把国旗图和头像图定在一起,我这里是垂直水平居中了 */
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%,-50%);
width: 200px;
height: 200px;
}
.head {
background: url(./cs头像.JPG) no-repeat;
background-size: cover;
}
.flag {
background: url(./国旗.jpg) no-repeat;
background-size: cover;
/* 在国旗图上使用mask搭配渐变 */
-webkit-mask: linear-gradient(110deg, #000 10%, transparent 70%, transparent);
}
(这里的国旗图用伪元素放上去也可以)
参考来源:https://mp.weixin.qq.com/s/KCYjr2O7XIpLb3QRXTJVrQ