返回
日地月公转
前端
2023-11-12 06:46:05
有手就会系列——实现日地月公转
前言
打工人的无奈,公司要求每个人都要进行培训。为了完成它,上网找出好几个demo,都没有勾起我动手实现一波的欲望。日常浏览掘金时,偶然看到一篇【中秋】纯CSS实现日地月的公转,决定就是它了。
实现效果
经过一番调优之后,最终效果如下:
[gif图]
实现过程
1. HTML结构
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<div class="container">
<div class="sun"></div>
<div class="earth"></div>
<div class="moon"></div>
</div>
</body>
</html>
2. CSS样式
.container {
width: 500px;
height: 500px;
position: relative;
}
.sun {
width: 100px;
height: 100px;
background-color: yellow;
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
}
.earth {
width: 50px;
height: 50px;
background-color: blue;
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
}
.moon {
width: 25px;
height: 25px;
background-color: white;
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
}
/* 动画 */
@keyframes sun-rotate {
0% {
transform: rotate(0deg);
}
100% {
transform: rotate(360deg);
}
}
@keyframes earth-rotate {
0% {
transform: rotate(0deg);
}
100% {
transform: rotate(360deg);
}
}
@keyframes moon-rotate {
0% {
transform: rotate(0deg);
}
100% {
transform: rotate(360deg);
}
}
.sun {
animation: sun-rotate 10s infinite linear;
}
.earth {
animation: earth-rotate 20s infinite linear;
}
.moon {
animation: moon-rotate 30s infinite linear;
}
3. JavaScript脚本
// 获取元素
const sun = document.querySelector('.sun');
const earth = document.querySelector('.earth');
const moon = document.querySelector('.moon');
// 创建动画
const sunRotateAnimation = sun.animate([
{ transform: 'rotate(0deg)' },
{ transform: 'rotate(360deg)' }
], {
duration: 10000,
iterations: Infinity,
easing: 'linear'
});
const earthRotateAnimation = earth.animate([
{ transform: 'rotate(0deg)' },
{ transform: 'rotate(360deg)' }
], {
duration: 20000,
iterations: Infinity,
easing: 'linear'
});
const moonRotateAnimation = moon.animate([
{ transform: 'rotate(0deg)' },
{ transform: 'rotate(360deg)' }
], {
duration: 30000,
iterations: Infinity,
easing: 'linear'
});
// 暂停动画
sunRotateAnimation.pause();
earthRotateAnimation.pause();
moonRotateAnimation.pause();
// 播放动画
document.querySelector('.play-button').addEventListener('click', () => {
sunRotateAnimation.play();
earthRotateAnimation.play();
moonRotateAnimation.play();
});
// 暂停动画
document.querySelector('.pause-button').addEventListener('click', () => {
sunRotateAnimation.pause();
earthRotateAnimation.pause();
moonRotateAnimation.pause();
});
结语
这样,我们就实现了日地月公转的动画效果。