css动画制作弹球
使用CSS动画制作弹球效果
创建一个弹球动画需要结合CSS的@keyframes规则和animation属性,模拟弹球的弹跳和移动效果。以下是实现方法:
HTML结构
<div class="ball"></div>
CSS样式
.ball {
width: 50px;
height: 50px;
background-color: #ff4757;
border-radius: 50%;
position: absolute;
bottom: 0;
left: 50%;
transform: translateX(-50%);
animation: bounce 2s infinite cubic-bezier(0.5, 0.05, 0.5, 1);
}
@keyframes bounce {
0%, 100% {
bottom: 0;
animation-timing-function: cubic-bezier(0.5, 0.05, 0.5, 1);
}
50% {
bottom: 300px;
animation-timing-function: cubic-bezier(0.05, 0.5, 0.5, 1);
}
}
关键点说明
贝塞尔曲线控制速度
通过cubic-bezier()函数调整弹跳的加速度和减速度:
- 下落时使用
cubic-bezier(0.05, 0.5, 0.5, 1)模拟重力加速 - 上升时使用
cubic-bezier(0.5, 0.05, 0.5, 1)模拟阻力减速
弹跳高度调整
修改@keyframes中50%对应的bottom值可改变弹跳高度,数值越大弹跳越高。
进阶效果:带水平移动的弹球
.ball {
/* 保持原有样式 */
animation: bounceAndMove 3s infinite;
}
@keyframes bounceAndMove {
0% {
bottom: 0;
left: 0;
}
25% {
bottom: 200px;
left: 25%;
}
50% {
bottom: 0;
left: 50%;
}
75% {
bottom: 150px;
left: 75%;
}
100% {
bottom: 0;
left: 100%;
}
}
性能优化建议
- 使用
transform替代bottom/left属性变化可获得更好的性能 - 为元素添加
will-change: transform;提示浏览器提前优化 - 避免同时激活过多动画,可能引起页面卡顿






