css帧动画制作视频
使用CSS关键帧(@keyframes)制作动画
定义关键帧动画,通过@keyframes规则指定动画在不同时间点的样式变化。例如创建一个元素从左到右移动的动画:
@keyframes slide {
0% {
transform: translateX(0);
}
100% {
transform: translateX(200px);
}
}
将动画应用到元素上,设置持续时间、延迟和重复次数等属性:
.box {
animation: slide 2s ease-in-out infinite;
}
结合HTML结构实现动画效果
创建需要动画的HTML元素,通常使用<div>或其他语义化标签:
<div class="animated-box"></div>
通过CSS为元素添加基础样式和动画属性:
.animated-box {
width: 100px;
height: 100px;
background-color: blue;
animation: bounce 1.5s infinite;
}
@keyframes bounce {
0%, 100% {
transform: translateY(0);
}
50% {
transform: translateY(-50px);
}
}
控制动画播放状态
使用animation-play-state属性可以暂停或运行动画,适合交互场景:
.animated-box:hover {
animation-play-state: paused;
}
通过JavaScript动态控制动画的播放状态:
const box = document.querySelector('.animated-box');
box.style.animationPlayState = 'running'; // 或 'paused'
实现复杂序列动画
创建多阶段关键帧动画,实现更复杂的运动效果:
@keyframes complex-animation {
0% {
transform: translate(0, 0) rotate(0deg);
background-color: red;
}
25% {
transform: translate(200px, 0) rotate(90deg);
}
50% {
transform: translate(200px, 200px) rotate(180deg);
background-color: blue;
}
100% {
transform: translate(0, 200px) rotate(360deg);
background-color: green;
}
}
优化动画性能
使用will-change属性预先告知浏览器元素将发生变化:
.animated-element {
will-change: transform, opacity;
}
优先使用CSS硬件加速属性如transform和opacity,避免使用top、left等属性触发重排:
@keyframes optimized {
to {
transform: scale(1.5);
opacity: 0.5;
}
}
响应式动画设计
结合媒体查询为不同设备尺寸调整动画参数:
@media (max-width: 600px) {
.animated-box {
animation-duration: 1s;
animation-name: mobile-animation;
}
}
创建帧动画精灵图(Sprite)
使用背景位置变化实现逐帧动画效果:
@keyframes run {
0% {
background-position: 0 0;
}
20% {
background-position: -100px 0;
}
/* 更多帧... */
100% {
background-position: -500px 0;
}
}
.character {
width: 100px;
height: 100px;
background-image: url('sprite-sheet.png');
animation: run 1s steps(6) infinite;
}





