收藏
评论

小程序实现自定义动画

小程序有自己的动画API----wx.createAnimation,他实现了CSS3的各种动画,很好用,但是有时我们需要逻辑层面的动画,这样我们就可以随心所欲的控制动画,js的requestAnimationFrame就是很好的动画函数,可以自己封装一个动画方法,代码如下:

//index.js
var id;//settimeout的id
 
Page({
data: {
 
},
onReady:function(){

    var $this = this;

   //开始动画

    this.animation(function(){
         if(condition){//动画结束条件
           $this.cancelAnimation();
         }
        callback();
    })
},
//返回动画函数
requestAnimationFrame: function (callback) {
    if (typeof requestAnimationFrame !== 'undefined') {
    return requestAnimationFrame;
    } else if (typeof webkitRequestAnimationFrame !== 'undefined') {
    return webkitRequestAnimationFrame;
    } else if (typeof mozRequestAnimationFrame !== 'undefined') {
    return mozRequestAnimationFrame
    } else {
        return function ( callback ) {
            return setTimeout(callback, 16);//不支持requestAnimationFrame 的补救措施
        };
    }
},
//返回关闭动画函数
cancelRequestAnimationFrame:function(id){
    if (typeof cancelAnimationFrame !== 'undefined') {
        return cancelAnimationFrame;
    } else if (typeof webkitCancelRequestAnimationFrame !== 'undefined') {
        return webkitCancelRequestAnimationFrame;
    } else if (typeof webkitCancelAnimationFrame !== 'undefined') {
        return webkitCancelAnimationFrame;
    } else if (typeof mozCancelRequestAnimationFrame !== 'undefined') {
        return mozCancelRequestAnimationFrame
    } else if (typeof mozCancelAnimationFrame !== 'undefined') {
        return mozCancelAnimationFrame
    }else {
        return function (id) {
        clearTimeout(id);
        };
    }
},
//实现动画,callback动画执行的函数
animation:function(callback){
    var c = this.requestAnimationFrame();
    var fn = function () {
        callback();
        id = c(fn);
    }
    id = c(fn);
},
//清除动画
cancelAnimation:function(){
    var cancel = this.cancelRequestAnimationFrame();
    cancel(id);
}
})



收藏

2 个评论

  • @阳
    @阳
    2018-01-09

    这里做兼容确实意义不大。我测试了一下,微信里面不支持requestAnimationFrame,所以其实这里走的是setTimeout。

    2018-01-09
    赞同
    回复 1
    • 🐚
      🐚
      2018-08-21

      我用setInterval代替,但是手机会发热,有没有什么好的解决方案?

      2018-08-21
      回复
  • 二月
    二月
    2018-01-09

    能用到小程序的微信版本都能支持requestAnimationFrame了吧,如果能,requestAnimationFrame做兼容性的必要性就不大了。

    2018-01-09
    赞同
    回复
登录 后发表内容