火箭飞行动画制作
html
<div class="scene">
<div class="rocket">
<img width="100" src="./rocket.png" alt="rocket">
</div>
</div>
- html代码比较简洁
- 只需写出通用的黑色场景
- 建立火箭rocket标签
- 插入火箭图片,默认图片大小100即可
css
body{
margin: 0;
padding: 0;
box-sizing: border-box;
}
.scene {
position: relative;
width: 100%;
height: 100vh;
background: #000;
overflow: hidden;
display: flex;
align-items: center;
justify-content: center;
}
.scene .rocket {
position: relative;
animation: animate 0.2s ease infinite;
}
@keyframes animate{
0%{
transform: translateY(-2px);
}
50%{
transform: translateY(2px);
}
}
.scene i {
position: absolute;
top: -200px;
background: rgba(255,255,255,0.5);
animation: animates linear infinite;
}
@keyframes animates{
from{
transform: translateY(0);
}
to{
transform: translateY(200vh);
}
}
.rocket::before {
content: '';
position: absolute;
bottom: -200px;
left: 50%;
transform: translateX(-50%);
width: 10px;
height: 200px;
background: linear-gradient(#00d0ff,transparent);
filter: blur(5px);
}
- 首先初始化body样式
- 给场景scene宽高占据全屏,并设置黑色背景,使用flex布局使其火箭垂直水平居中
- 火箭样式加入css3新特性动画标签animation
- 并使之上下跳动
- 再对创建对i标签进行雨滴样式改造
- 使用定位,动画效果,铺满全屏
- 最后加入火箭喷气效果,filter是滤镜效果,给出模糊感,看的更接近现实
介绍下animation语法
animation: name duration timing-function delay iteration-count direction fill-mode play-state;
CSS3 transform 和 filter(滤镜) 属性
transform属性文档
filter属性
<script type="text/javascript">
function start () {
let count = 50;
let i = 0;
let scene = document.querySelector('.scene');
while (i < count){
let star = document.createElement('i');
let w = Math.floor(Math.random() * window.innerWidth);
let h = Math.random() * 100;
let duartion = Math.random() * 1;
star.style.width = 1 + 'px';
star.style.height = 50 + h + 'px';
star.style.left = w + 'px';
star.style.animationDuration = duartion + 's';
scene.appendChild(star);
i++;
}
}
start();
</script>
- 定义两个变量count 和 i
- 通过DOM操作获得场景scene标签都元素属性
- 通过while循环对比i和count大小,可以控制i标签的数量,快慢,从而可以更好展示火箭飞行效果
- 创建出i元素的节点
- 再使用向上取整,随机函数获取,获取i标签的随机高,随机下落时间和随机下落位置,宽度固定1px即可
- 最后把star子节点插入到scene下,i++循环,调用函数启动
