css3实现

1、 css3 transition过渡效果

严格来说,过渡不应该算是动画,动画应特指持久化的动画

<!--思路:起点和终点会瞬时改变,过渡的意思是按某种函数曲线改变,如均匀变化-->
div {
    width:100px;
}
div:hover {
    width:200px;
    transition: width 2s linear 1s;
    -moz-transition: width 2s linear 1s;    /* Firefox 4 */
    -webkit-transition: width 2s linear 1s;    /* Safari 和 Chrome */
    -o-transition: width 2s linear 1s;    /* Opera */
}

2、 css3 animation动画

<!--思路:不需要设定起终点,由动画函数(即关键帧keyframe)设置起终点-->
div  {
    animation: mymove 5s infinite delay count direction;
}
@keyframes mymove {
    from: {left:0px}
    to:   {left:100px}
}
  • 注意:性能(本质上取决于引擎实现)较好,兼容性差

js动画

1、 定时器实现

<!--思路:用计时器频繁修改元素位置,缺点是重绘次数多少不容易控制且定时不精确-->
function animate(obj, target){//obj:选中的属性, target:目标坐标
       obj.timer = setInterval(function(){
           if(obj.offsetLeft > target){
               clearInterval(obj.timer);
           }
           obj.style.left = obj.offsetLeft +10 +"px";
       },30);
 }

2、 H5的requestAnimationFrame

它的实现封装了定时器时间间隔的细节,既不会过多造成开销过大,也不会过少造成动画卡顿,对dom操作、隐藏元素动画都有优化

  • 以进度条实现为例:
<!--思路:requestAnimationFrame(callback)调用;cancelAnimationFrame(timer)取消-->
window.requestAnimationFrame = window.requestAnimationFrame || window.mozRequestAnimationFrame || window.webkitRequestAnimationFrame || window.msRequestAnimationFrame;
var start = null;
var ele = document.getElementById("test");
var progress = 0;

function step(timestamp) {
    progress += 1;
    ele.style.width = progress + "%";
    ele.innerHTML=progress + "%";
    if (progress < 100) {
        requestAnimationFrame(step);  c
    }
}
requestAnimationFrame(step);
document.getElementById("run").addEventListener("click", function() {
    ele.style.width = "1px";
    progress = 0;
    requestAnimationFrame(step);
}, false);

3、 H5 canvas

定义了一些绘制图形的api,使用requestAnimationFrame和setInterval来反复擦除和重回动画

其他

  • 如一些动画插件、jquery动画插件,大多数是封装了CSS3动画的方法,均基于以上api,可以根据需要解构或调用