这段代码创建了一个动态的吃豆人动画,通过 CSS 动画技术模拟了吃豆人的动作和眼睛的移动,为页面添加了趣味性的视觉效果。
演示效果
HTML&CSS
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>公众号关注:前端Hardy</title>
<style>
body {
margin: 0;
padding: 0;
background: #212121;
display: flex;
align-items: center;
justify-content: center;
height: 100vh;
}
.loader {
display: flex;
justify-content: space-between;
}
.pacman {
width: 5em;
aspect-ratio: 1;
border-radius: 50%;
background: radial-gradient(farthest-side, #000 98%, #0000) 1.7em 0.61em/.8em .8em no-repeat,
#ffcc00;
box-shadow: .2em -.6em 1.2em 0em inset rgba(0, 0, 0, 0.7);
animation: l4 .5s infinite steps(5) alternate;
z-index: 999;
}
.point {
margin-top: 2em;
position: absolute;
margin-left: .4em;
width: 1em;
height: 1em;
background-color: #fff;
border-radius: 50%;
}
.p1 {
margin-left: 8em;
animation: moove-p1 2s linear infinite;
}
.p2 {
margin-left: 15em;
animation: moove-p2 2s linear infinite;
}
@keyframes moove-p1 {
0% {
margin-left: 8em;
}
100% {
margin-left: 0em;
}
}
@keyframes moove-p2 {
0% {
margin-left: 16em;
}
100% {
margin-left: 8em;
}
}
@keyframes l4 {
0% {
clip-path: polygon(50% 50%, 100% 0, 100% 0, 0 0, 0 100%, 100% 100%, 100% 100%)
}
100% {
clip-path: polygon(50% 50%, 100% 65%, 100% 0, 0 0, 0 100%, 100% 100%, 100% 35%)
}
}
</style>
</head>
<body>
<div class="loader">
<div class="pacman"></div>
<div class="point p1"></div>
<div class="point p2"></div>
</div>
</body>
</html>
HTML 结构
- loader: 创建一个类名为“loader”的 div 元素,用于包含吃豆人动画和两个点(代表吃豆人的眼睛)。
CSS 样式
- body: 设置页面的边距、填充、背景色、显示方式和高度。
- .loader: 设置容器的布局为 flex,并使子元素间隔均匀。
- .pac-man: 设置吃豆人的样式,包括尺寸、宽高比、边框半径、背景渐变、阴影和动画。
- .point: 设置点(吃豆人的眼睛)的样式,包括位置、尺寸、背景色和边框半径。
- .p1 和 .p2: 分别设置两个点的位置和动画。
- @keyframes moove-p1 和 @keyframes moove-p2: 定义两个关键帧动画,分别用于控制两个点的左右移动。
- @keyframes l4: 定义吃豆人嘴巴开合的动画。
- .pac-man: 通过animation属性应用了l4动画,使吃豆人的嘴巴能够开合。
- .p1 和 .p2: 通过animation属性应用了moove-p1和moove-p2动画,使两个点能够左右移动,模拟吃豆人的眼睛。