I
I
Isaac Clark2013-02-15 12:08:20
JavaScript
Isaac Clark, 2013-02-15 12:08:20

How to improve/smooth the backgroundPosition animation in JavaScript?

Hello, tell me please.
There is an EaseOut animation that scrolls the background a certain distance.
If the distance is not large, then the effect works fine, but if I set the animation to scroll by about >= 300px, then the animation turns out to be some kind of “torn” ... And another question, when the distance is not large, then the effect is slow, but if >= 300px, then the animation tries to cover the distance in the same time, but naturally at a higher speed.
Please help me to make sure that regardless of the distance, the speed of the animation is the same.
Here is the code:

function set_animate(opts) {
        var start = new Date,
            timer = setInterval(function () {
                var progress = (new Date - start) / opts.duration;

                if (progress > 1) {
                    progress = 1;
                }

                opts.step(opts.delta(progress));

                if (progress == 1) {
                    clearInterval(timer);
                }
            }, 34);
    }

    function get_animate(elem, delta, duration) {
        var to = 58;

        set_animate({
            delay: 10,
            duration: duration || 1000,
            delta: delta,
            step: function (delta) {
                $(elem).css('backgroundPosition', '0 -' + to * delta + 'px');
            }
        });
    }

    function bounce(progress) {
        for (var a = 0, b = 1, result; 1; a += b, b /= 2) {
            if (progress >= (7 - 4 * a) / 11) {
                return -Math.pow((11 - 6 * a - 11 * progress) / 4, 2) + Math.pow(b, 2);
            }
        }
    }

    function makeEaseOut(delta) {
        return function (progress) {
            return 1 - delta(1 - progress);
        }
    }

    get_animate(slide.number_1, makeEaseOut(bounce));


Thank you very much for your help and your time.

Answer the question

In order to leave comments, you need to log in

2 answer(s)
G
giggigi, 2013-02-15
@gigigi

Try using css transition, it should work smoother.
Here is an example jsfiddle.net/hfXSs/

R
Roman, 2013-02-15
@beat

use requestAnimationFrame instead of setInterval

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question