javascript - 原生js一般是如何实现运动效果的?
怪我咯
怪我咯 2017-04-11 13:27:02
[JavaScript讨论组]

我移动端一般就是用css3的动画,pc端都是用jq那几个常用动画就没用过其他的了,想问下大家用原生js实现运动效果都是怎么实现的?会不会很麻烦或者用什么库吗?

怪我咯
怪我咯

走同样的路,发现不同的人生

全部回复(5)
黄舟

一般是:

setInterval(function(){
    //dosomething...
},1000/60);

或者:

window.requestAnimationFrame(function(/* time */ time){
  // time ~= +new Date // the unix time
});

或者:

// shim layer with setTimeout fallback
window.requestAnimFrame = (function(){
  return  window.requestAnimationFrame       ||
          window.webkitRequestAnimationFrame ||
          window.mozRequestAnimationFrame    ||
          function( callback ){
            window.setTimeout(callback, 1000 / 60);
          };
})();


// usage:
// instead of setInterval(render, 16) ....

(function animloop(){
  requestAnimFrame(animloop);
  render();
})();
// place the rAF *before* the render() to assure as close to
// 60fps with the setTimeout fallback.

或者(更牢靠的封装):

(function() {
    var lastTime = 0;
    var vendors = ['webkit', 'moz'];
    for(var x = 0; x < vendors.length && !window.requestAnimationFrame; ++x) {
        window.requestAnimationFrame = window[vendors[x]+'RequestAnimationFrame'];
        window.cancelAnimationFrame =
          window[vendors[x]+'CancelAnimationFrame'] || window[vendors[x]+'CancelRequestAnimationFrame'];
    }

    if (!window.requestAnimationFrame)
        window.requestAnimationFrame = function(callback, element) {
            var currTime = new Date().getTime();
            var timeToCall = Math.max(0, 16 - (currTime - lastTime));
            var id = window.setTimeout(function() { callback(currTime + timeToCall); },
              timeToCall);
            lastTime = currTime + timeToCall;
            return id;
        };

    if (!window.cancelAnimationFrame)
        window.cancelAnimationFrame = function(id) {
            clearTimeout(id);
        };
}());
PHP中文网

setInterval和setTimeout,可能你需要这个

迷茫

配合timing-function用
cubic-bezier
http://cubic-bezier.com/

PHP中文网

既然你用jquery,那么不妨去看一下jq关于动画、过渡实现的js代码

怪我咯

https://segmentfault.com/a/11...

热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 举报中心 意见反馈 讲师合作 广告合作 最新更新 English
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号