如何使用CSS \ cubic-bezier实现正弦函数?

时间:2014-08-11 08:05:39

标签: javascript css css-animations

我将在正弦函数中实现CSS宽度动画,如:

但是使用cubic-bezier,我只能设置四个参数,例如transition: all 500ms cubic-bezier(0.695, 0.015, 1.000, 0.275);

使用CSS动画实现这一目标的位置是什么?或者如何在JS中做到这一点?

1 个答案:

答案 0 :(得分:3)

您可以使用cubic-bezier()来模仿正弦函数

请查看此资源以进行正弦逼近:Sine approximation using cubic Bézier curves

使用4个关键帧和cubic-bezier()和值:

cubic-bezier(0,0,0.3642,1)
cubic-bezier(0.6358,0,1,1)
cubic-bezier(0,0,0.3642,1)
cubic-bezier(0.6358,0,1,1)

将移动具有正弦函数轨迹的对象。

我为您的案例进行了演示。纯CSS解决方案,请看一下:

演示

.box {
    width: 20px;
    height: 20px;
    background-color: royalblue;

    animation-fill-mode: forwards;
    animation:
            sine1-1 0.3s 1 0s cubic-bezier(0,0,0.3642,1),
            sine1-2 0.3s 1 0.3s cubic-bezier(0.6358,0,1,1),
            sine1-3 0.3s 1 0.6s cubic-bezier(0,0,0.3642,1),
            sine1-4 0.3s 1 0.9s cubic-bezier(0.6358,0,1,1),
            sine2-1 0.3s 1 1.2s cubic-bezier(0,0,0.3642,1),
            sine2-2 0.3s 1 1.5s cubic-bezier(0.6358,0,1,1),
            sine2-3 0.3s 1 1.8s cubic-bezier(0,0,0.3642,1),
            sine2-4 0.3s 1 2.1s cubic-bezier(0.6358,0,1,1),
            sine3-1 0.3s 1 2.4s cubic-bezier(0,0,0.3642,1),
            sine3-2 0.3s 1 2.7s cubic-bezier(0.6358,0,1,1);
}

@keyframes sine1-1 {
    0% {transform: translateY(0)}
    100% {transform: translateY(-100px)}
}

@keyframes sine1-2 {
    0% {transform: translateY(-100px)}
    100% {transform: translateY(0)}
}

@keyframes sine1-3 {
    0% {transform: translateY(0)}
    100% {transform: translateY(80px)}
}

@keyframes sine1-4 {
    0% {transform: translateY(80px)}
    100% {transform: translateY(0)}
}

@keyframes sine2-1 {
    0% {transform: translateY(0)}
    100% {transform: translateY(-60px)}
}

@keyframes sine2-2 {
    0% {transform: translateY(-60px)}
    100% {transform: translateY(0)}
}

@keyframes sine2-3 {
    0% {transform: translateY(0)}
    100% {transform: translateY(40px)}
}

@keyframes sine2-4 {
    0% {transform: translateY(40px)}
    100% {transform: translateY(0)}
}

@keyframes sine3-1 {
    0% {transform: translateY(0)}
    100% {transform: translateY(-20px)}
}

@keyframes sine3-2 {
    0% {transform: translateY(-20px)}
    100% {transform: translateY(0)}
}

.horizontal {
    animation: move-horizontal 3s 1 linear;
}

@keyframes move-horizontal {
    0% {transform: translateX(0)}
    100% {transform: translateX(400px)}
}

.wrap {
    background-color: #bfbfbf;
}

.margin {
    width: 100px;
    height: 100px;
}
<div class="margin"></div>
<div class="wrap">
    <div class="horizontal">
        <div class="box"></div>
    </div>
</div>