思路如下:
- 固定的外面的盒子,循环添加多个
span
作为像素的点/块 - 通过定位和动画关键帧来操控旋转、平移效果
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="style.css">
<title>像素图像</title>
</head>
<body>
<div class="box">
<div id="pixel"></div>
</div>
<script>
let w = 70;
let h = 55;
function pixel() {
for (let i = 0; i < h; i++) {
for (let j = 0; j < w; j++) {
let span = document.createElement('span')
let random = Math.random() * 2;
let randomDelay = random.toFixed(2)
document.getElementById('pixel').appendChild(span)
span.style.left = j * 5 + 'px';
span.style.top = i * 5 + 'px'
span.style.backgroundPosition = -j * 5 + 'px ' + -i * 5 + 'px, center';
span.style.animationDelay = randomDelay + 's'//动画在启动前的延迟间隔。
}
}
}
pixel()
</script>
</body>
</html>
* {
margin: 0;
padding: 0;
box-sizing: border-box;
}
body {
display: flex;
justify-content: center;
align-items: center;
min-height: 100vh;
background-color: black;
}
.box {
position: relative;
width: 400px;
height: 400px;
}
.box span {
position: absolute;
width: 5px;
height: 5px;
background: url(bizhi.jpeg);
background-repeat: no-repeat;
animation: animate 10s linear infinite;
}
@keyframes animate {
0%,
10% {
scale: 1;
rotate: 0deg;
translate: 0 0;
transform-origin: center;
}
20%,
30% {
scale: 0.5;
rotate: 0deg;
translate: 0 0;
transform-origin: center;
}
40% {
scale: 0.5;
rotate: 360deg;
translate: 150px 0;
transform-origin: 100px;
}
70% {
scale: 0.5;
rotate: 720deg;
translate: -150px 0;
transform-origin: -100px;
}
90% {
scale: 2.5;
rotate: 0deg;
translate: 0 0;
transform-origin: center;
}
100% {
scale: 1;
rotate: 0deg;
translate: 0 0;
transform-origin: center;
}
}
参考:
bilibili视频链接