Adding easing on requestAnimationFrame

一笑奈何 提交于 2019-12-01 06:45:34

I think I've found an answer for you. It's based on this library

First, I would just grab a function from that site

function inOutQuad(n){
    n *= 2;
    if (n < 1) return 0.5 * n * n;
    return - 0.5 * (--n * (n - 2) - 1);
};

Then, I would use a modified form of the example code, something like this

function startAnimation(domEl){
    var stop = false;

    // animating x (margin-left) from 20 to 300, for example
    var startx = 20;
    var destx = 300;
    var duration = 1000;
    var start = null;
    var end = null;

    function startAnim(timeStamp) {
        start = timeStamp;
        end = start + duration;
        draw(timeStamp);
    }

    function draw(now) {
        if (stop) return;
        if (now - start >= duration) stop = true;
        var p = (now - start) / duration;
        val = inOutQuad(p);
        var x = startx + (destx - startx) * val;
        $(domEl).css('margin-left', `${x}px`);
        requestAnimationFrame(draw);
    }

    requestAnimationFrame(startAnim);
}

I might change how 'stop' is calculated, I might write something to ensure that it ends on destx, etc, but that's the basic format

Showing it in this jsfiddle

I'm actually kinda proud of this one. I've been wanting to figure this out for a while. Glad I had a reason to.

You can create your own ease function and use it inside your frame function:

var ease = function() {
    var x = 0;
    return function(x_new) {
        x = (x_new+x)*.5;
        return x;
    }
}();

function frame() {
  $('.images-gallery').css({
    'transform': 'translateX('+ -ease(mouseXPerc) +'%)'
  });
  requestAnimationFrame(frame);
}

requestAnimationFrame(frame);
$(document).on('mousemove',function(e){
  mouseXPerc = e.pageX/containerWidth*100;

});
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!