通过clip-path实现舞台聚光灯效果

1,258 阅读2分钟

背景

万圣节时候想要在销售页面的KV做一个灯光来回扫的效果,在灯光扫到的地方是白天形象,衣冠整齐,灯光没有扫到的地方是黑夜的情况,各种☠️

类似这样

分析

1、白天和黑夜应该是两张不同的图

2、将白天的图放到黑夜的图上面

3、将上面的图层使用css的clip-path裁剪成一个手电筒光束的效果

4、通过不停的重复改变裁剪的位置做一个手电筒光速移动的效果

clip-path介绍

css的属性 clip-path就是裁剪路径,默认属性是none,其他属性值有inset(),circle(),ellipse(),polygon()

circle(r at x y),圆形的绘制

参数是半径和坐标

div{
    clip-path: circle(50% at 50% 50%);//圆心50% 50%半径为50%
}

ellipse(r1 r2 at x y),椭圆的绘制

参数是x轴半径,y轴半径,定位椭圆的坐标

div{
    clip-path: ellipse(30% 20% at 50% 50%); // x半径30% y半径20% 中心点位置50% 50%
}

inset(t r b l round v1 v2 v3 v4),画圆角

参数是 上右下左 round t半径1 r半径2 b半径3 l半径4 (上右下左指的是距离上右下左的距离)

div{
    clip-path: inset(0 20% 20% 0% round 10% 0% 10% 0% )
}

polygon(x1 y1, x2 y2, x3 y3, x4 y4, x5 y5, ...),多边形的绘制

参数是逆时针顺序点的坐标

div {
  clip-path: polygon(0% 60%, 20% 0%, 60% 0%, 40% 60%)
}

--备注-- 可以通过 编辑clip-path 进行path的编辑

实现

1、将两张图片定位到同一个位置

2、通过z-index将要裁剪的图放到上面

3、通过css添加animation将图不停的裁剪

实现代码如下

<!DOCTYPE html>
<html lang="en">
<head>
	<meta charset="UTF-8">
	<title>Document</title>
	<style type="text/css">
		.wrap{
			width: 500px;
			height: 300px;
			margin: 50px auto;
			position: relative;
		}
		.inner1{
			position: absolute;
			left: 0;
			top: 0;
			width: 100%;
			height: 100%;
			background: blue;
			z-index: 2;
			animation: move linear 3s infinite;
		}
		.inner2{
			position: absolute;
			left: 0;
			top: 0;
			width: 100%;
			height: 100%;
			background: black;
			z-index: 1;
		}
		@keyframes move{
			0% {
				clip-path: polygon(45% 0, 55% 0, 70% 100%, 30% 100%);
			}
			25% {
				clip-path: polygon(40% 0, 50% 0, 30% 100%, -20% 100%);
			}
			50% {
				clip-path: polygon(45% 0, 55% 0, 70% 100%, 30% 100%);
			}
			75% {
				clip-path: polygon(50% 0, 60% 0, 120% 100%, 80% 100%);
			}
			100%{
				clip-path: polygon(45% 0, 55% 0, 70% 100%, 30% 100%);
			}
		}
	</style>
</head>
<body>
	<div class="wrap">
		<div class="inner1"></div>
		<div class="inner2"></div>
	</div>
</body>
</html>