写在最前面
- 最近做一个关于抽奖活动的项目,会涉及到很多动画,这里来探讨一下 scss 函数和 css 动画的制作
需求:如图
- 一个打开的盒子,其中有许多不规则的星星✨不规则的运动动,看着这个复杂的动画,我不禁周冬雨附身--小黄鸭眉头一皱.gif。
- 已经好久没写动画的我该如何入手,在仅限的 css 知识中知道 animate 动画。
思考
- 1、盒子弹跳动画
- 2、光幕出现,阴影的出现动画
- 3、盖子不规则飞行
- 4、星星不规则飞行
实现
- 1、
transform: scaleY() translate()
实现盒子弹跳 - 2、
opacity
实现光幕和阴影 - 3、
transform: rotateZ()
盖子飞行,翻转 - 4、
top left transform: translate()
星星运动
大概的思路都有了开始动手,写一个盖子飞行的动画
// 盒子居中布局
.stars{
opacity: 0;
}
.box{
top:50%;
left:50%;
position:absolute;
transform: translate(-50%,-50%);
}
// 基础 keyframes 函数
@mixin keyframes($animationName) {
@keyframes #{$animationName} {
@content;
}
}
// 由于是 translate 布局,这里改变定位使用 translate
@mixin animate-bounce($name:'bounce', $time: 1.5s, $animateFunc: linear) {
animation: $name $time ?animateFunc;
@include keyframes($name) {
0% {
transform: scaleY(1) translate(-50%, -50%);
}
8% {
transform: scaleY(0.98) translate(-50%, -48%);
}
50% {
transform: scaleY(1) translate(-50%, -70%);
}
100% {
transform: scaleY(1) translate(-50%, -50%);
}
}
}
}
@mixin animate-box-cover-fly($name:'box-cover-fly', $time: 1.5s, $animateFunc: linear){
animation: $name $time ?animateFunc;
@include keyframes($name) {
0% {
top: 23%;
left: 50%;
}
100% {
top: 5%;
left: 62%;
transform: translate(-20%, -50%) rotateZ(26deg);
}
}
}
}
// 盒子弹跳
.box-bounce{
@include animate-bounce('bounce');
}
.box-cover-fly{
@include animate-box-cover-fly('box-cover-fly');
}
思考
-
写到这里时候发现代码量会很多,即使用函数的形式,复写动画路径,具体实现中,发现效果并不好也不能完全复刻设计给的动画。
-
然后 google 了一下动画的实现方法,发现了
帧动画,和雪碧图
。虽然这两个知识点早就听说过,但是使用的时候都是分开使用的。结合起来的时候也能做动画效果,说做就做,先写一个 demo -
html
<div className="step-box" />
@mixin animate-spite-box($width: 134px) {
background: url('https://uploads.codesandbox.io/uploads/user/abc364e4-ea65-4398-a1dc-df2645675b64/U59a-lightbulb.png') 0 0 no-repeat;
background-size: cover;
animation: spite-box 1s steps(4) infinite;
@include keyframes(spite-box) {
from {
background-position: -8*$width;
}
to {
background-position: -12*$width;
}
}
}
$box-width: 134px
$box-height: 113px;
.step-box{
width: $box-width;
height: $box-height;
@include animate-spite-box($box-width);
}
先来看一个栗子🌰
@mixin keyframes($animationName) {
@keyframes #{$animationName} {
@content;
}
}
@mixin animate-spite-box($width: 134px) {
background: url('https://uploads.codesandbox.io/uploads/user/abc364e4-ea65-4398-a1dc-df2645675b64/U59a-lightbulb.png') 0 0 no-repeat;
background-size: cover;
animation: spite-box 1s steps(4) infinite;
@include keyframes(spite-box) {
from {
background-position: -8*$width;
}
to {
background-position: -12*$width;
}
}
}
.step-box{
width: 134px;
height: 113px;
@include animate-spite-box(134px);
}
- 看看上面面的的 CodePen-demo
决定采用雪碧图和 step 帧动画来实现
- 学习了上面的栗子,我们来制作自己的雪碧图和逐帧动画。
- 运用雪碧图的 background-position 位置移动动画,和 animate step 函数。
- 根据设计提供的png图,制作雪碧图,使用了下面的网站,网站会自动计算出每张图的位置,然后我们写在 background-postion 中,然后按照 demo 的方法完成我们的帧动画就可以了。
- www.toptal.com/developers/…
一些知识点
css3 animate
- animate: step 逐帧动画
- animation-fill-mode: forwards; 动画完成后保持现在的样式
- animation-iteration-count: infinite 循环动画