叨逼逼

我在设计个人简历主界面的时候,想将背景做成行星绕着恒星转的画面。这就需要css中的animation来实现椭圆运动。

开始造作

让我们看一下菜鸟教程css文档中有关animation的介绍。

菜鸟教程animation介绍

animation-timing-function可以设置速度曲线,即是可以通过该属性修改物体的运动速度和加速度。这正是我们需要的。

让我们思考一下,将椭圆的短轴无限缩小,椭圆的长轴无限扩大。则该椭圆将变得十分扁平,物体绕该椭圆运动就像绕一条直线做往返运动。如gif图所示。

所以我设置如下的css样式。

#test{
width: 200px;
height: 200px;
background-color: rebeccapurple;
animation: actionX 2s linear 0s infinite alternate,
actionY 2s linear 0s infinite alternate;
position: absolute;
}
@keyframes actionX{
0%{
left: 0px;
}
100%{
left: 600px;
}
}
@keyframes actionY{
0%{
top: 200px;
}
100%{
top: 0px;
}
}

得到如下gif图所示效果。

物体做椭圆运动,则其分解在X轴和Y轴方向上的速度状态有四种:(1)X轴速度为正,Y轴速度为正(2)X轴速度为正,Y轴速度为负(3)X轴速度为负,Y轴速度为负(4)X轴速度为负,Y轴速度为正。

于是,我设置如下css样式。

#test{
width: 200px;
height: 200px;
background-color: rebeccapurple;
animation: actionX 2s linear -1s infinite alternate,
actionY 2s linear 0s infinite alternate;
position: absolute;
}
@keyframes actionX{
0%{
left: 0px;
}
100%{
left: 600px;
}
}
@keyframes actionY{
0%{
top: 200px;
}
100%{
top: 0px;
}
}

说明:当animation-iteration-count设置为infinite时,物体会做往返运动。若设置animation-delay为0s,则两个运动是沿直线运动的;若像上边的css样式所示,将ationX动画的animation-delay设置为-1s,即是提前执行完往返运动中四分之一个周期,所以物体在left为300px和top为200px的位置开始运动,向右上方运动四分之一个周期;随后物体在X轴上开始做返回运动(速度变为负),此时物体在Y轴上速度仍为正,整个物体往左上方运动;这时物体在Y轴上开始做返回运动(速度变为负),此时物体在X轴上的速度仍为负,整个物体往左下方运动;之后物体在X轴开始一个新的周期(速度重新变为正),此时物体在Y轴上的速度仍为负,整个物体往右下方运动。

得出如下gif图所示效果。
看,是不是有点像椭圆了,只不过运动轨迹圆滑,物体绕着一个菱形轨迹运动。

我接着设置了animation-timing-function为ease-in-out,使物体运动看起来圆滑。设置之后的css样式如下。

#test{
width: 200px;
height: 200px;
background-color: rebeccapurple;
position: absolute;
animation: actionX 2s ease-in-out -1s infinite alternate,
actionY 2s ease-in-out 0s infinite alternate;
}
@keyframes actionX{
0%{
left: 0px;
}
100%{
left: 600px;
}
}
@keyframes actionY{
0%{
top: 200px;
}
100%{
top: 0px;
}
}

得到的效果如下gif图所示。

其实还可以设置为cubic-bezier(0.36,0,0.64,1),得出来的效果也是椭圆。

我经过测试,cubic-bezier(x1,y1,x2,y2)中y1设置为0,y2设置为1,x1设置在0.25到0.5之间,x2设置在0.5到0.75之间都可以产生能看的过去的椭圆运动效果。

更多推荐

html/css椭圆运动