首页 > 技术文章 > cubic-bezier贝塞尔曲线css3动画工具

hsprout 2016-02-26 22:15 原文

今天在一本叫《HTML5触摸界面设计与开发》上看到一个做弹跳球的复杂动画效果,首先加速下降,停止,然后弹起时逐渐减速。是用cubic-bezier贝塞尔曲线来完成的。所以特地去学习了一下关于cubic-bezier贝塞尔曲线。

cubic-bezier比较少用,因为PC端中,有浏览器不兼容。但是手机端中,可以使用并带来炫酷的动画及体验。

缓动函数:http://www.xuanfengge.com/easeing/easeing/

cubic-bezier:http://cubic-bezier.com/

cubic-bezier是贝塞尔曲线中的绘制方法。

css3中常用的几个动画效果:

1  ease: cubic-bezier(0.25, 0.1, 0.25, 1.0)
2  linear: cubic-bezier(0.0, 0.0, 1.0, 1.0)
3  ease-in: cubic-bezier(0.42, 0, 1.0, 1.0)
4  ease-out: cubic-bezier(0, 0, 0.58, 1.0)
5  ease-in-out: cubic-bezier(0.42, 0, 0.58, 1.0)

贝塞尔曲线通过四个点来定义一条曲线。这四个值描述了控制点的位置p1,p2,(x1,y1,x2,y2),值得范围在0-1之间,其他两个点永远是p0(0,0)p3(1,1)。控制点是控制图中的曲线,这些曲线会让球在弹起和下落的过程中,给予(正或负)加速度。(0,.27,.32,1)在上升过程中起作用,(1,0,0.96,0.91)在下降中起作用。

 

我们现在已经大概了解了一点贝塞尔曲线,接下来就看一个弹跳球的例子。

HTML部分:

1 <div id="ball"></div>
2 <div id="floor"></div>

CSS部分:

 1 body{margin:0;padding:0;}
 2 #ball{
 3   background:red;
 4   height:100px;
 5   width:100px;
 6   position:absolute;
 7   top:10px;
 8   left:20px;
 9   border-radius:50px;
10 }
11 #floor{
12   position:absolute;
13   bottom:10px;
14   left:0px;
15   width:350px;
16   height:1px;
17   border-top:5px solid brown;
18 }

 检测正确的制造商前缀:

 1 (function(){
 2  
 3   var down=false, 
4
trans='transition',
5
eventName='transitionend'; 6 if(typeof document.body.style.webkitTransition==='string'){ 7 trans='webkitTransition'; 8 eventName='webkitTransitionEnd'; 9 }else if(typeof document.body.style.MozTransition==='string'){ 10 trans='MozTransition'; 11 } 12 })();
document.body.style.webkitTransition获取以webkit为前缀的transition
在WebKit引擎的浏览器中,当css3的transition动画执行结束时,触发webkitTransitionEnd事件。
下面是一个反弹函数:(这个函数写在上面自动执行的函数中)
 1 var ball=document.getElementById('ball');
 2       floor=document.getElementById('floor');
 3 
 4 function bounce(){
 5      if(down){
 6          ball.style[trans]="Top 1s cubic-bezier(0,.27,.32,1)";
 7          ball.style.top='10px';
 8          down=false;
 9 }else{
10     ball.style[trans]="Top 1s cubic-bezier(1,0,0.96,0.91)";
11     ball.style.top=(floor.offsetTop-100)+'px';
12     down=true;
13 }
14 }
15 
16 ball.addEventListener(eventName,bounce);
17 bounce();
18 })();

 

 


推荐阅读