CSS3贝塞尔曲线实现嫦娥奔月(cubic-bezier)

2,729 阅读2分钟

我正在参加中秋创意投稿大赛,详情请看:中秋创意投稿大赛

最近在看animation模块,其中animation-timing-function 和 transition-timing-function两个属性来控制动画速度分别提供了ease,liner,ease-in,ease-out,ease-in-out几个预设速度,还可以同过cubic-bezier来自定义速度,想要深入了解CSS3动画,实现随心所欲的动画效果,还是有必要理解下其中的原理。

在了解 cubic-bezier 之前,你需要对 CSS3 中的动画效果有所认识,它是 animation-timing-function 和 transition-timing-function 中一个重要的内容。

例子:transition:all 1s cubic-bezier(.21,.2,.65,.1)

cubic-bezier 又称三次贝塞尔,主要是为 animation 生成速度曲线的函数,规定是 cubic-bezier(, , , )。 我们可以从下图中简要理解一下 cubic-bezier:

741039-305ff3a5f2e6de1c.webp

从上图我们需要知道的是 cubic-bezier 的取值范围:

P0:默认值 (0, 0) P1:动态取值 (x1, y1) P2:动态取值 (x2, y2) P3:默认值 (1, 1)

我们需要关注的是 P1 和 P2 两点的取值,而其中 X 轴的取值范围是 0 到 1,当取值超出范围时 cubic-bezier 将失效;Y 轴的取值没有规定,当然也毋须过大。

最直接的理解是,将以一条直线放在范围只有 1 的坐标轴中,并从中间拿出两个点来拉扯(X 轴的取值区间是 [0, 1],Y 轴任意),最后形成的曲线就是动画的速度曲线。

741039-4016cb02499bb127.webp

这里提供一个贝塞尔曲线(cubic-bezier)在线生成地址可供拷贝:

英文版

中文版

废话不多说,学习了cubic-bezier,下面就用这个cubic-bezier贝塞尔曲线实现嫦娥奔月效果,仅供娱乐,不喜勿碰哈:

<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<meta http-equiv="Content-Language" content="zh-cn">
<title>中秋嫦娥奔月</title>
<style type="text/css">
*{margin:0; padding:0;}
html,body{width:100%; height:100%;}
.main{background:url(images/bg.jpg)no-repeat; background-size: 100% 100%;}
.wrap{position:relative; width:1200px; height:100%; margin:0 auto;}
.ball{
   width: 320px;
   height: 257px;
   background:url(images/change.png)no-repeat;
   background-size: 100% 100%;
   position: absolute;
   bottom: 0;
   z-index: 10;
   left: 0;
}

/*定义动画的流程*/
.run_top_right {
  display: block;
  animation: run-right-right 3s 0.4s 1 linear, run-right-top 3s 0.4s 1 cubic-bezier(.66,.1,1,.41);
  /*animation: run-right-right 3s 0.4s 1 linear, run-right-top 3s 0.4s 1 ease-out;*/
  animation-fill-mode: forwards;
}

/*向上走的动画初始及结尾值*/
@keyframes run-right-top {
  0% {
    bottom: 40px;
  }
  100% {
    bottom: 580px;
  }
}
/*向上右的动画初始及结尾值*/
@keyframes run-right-right {
  0% {
    left: 40px;
    transform: scale(1);
  }100% {
    left: 880px;
    transform: scale(0.8);
  }
}
</style
</head>
<body>
<div class="main">
	<div class="wrap">
	 <div class="ball run_top_right"></div>
	</div>
</div>
</body>
</html>
<script>
</script>

效果如下:

1.2.gif

素材图:

change.png