0

I have a pattern background animation in jQuery made like this.

        banner.css('backgroundPosition', x + 'px' + ' ' + y + 'px');

        window.setInterval(function() {
            banner.css("backgroundPosition", x + 'px' + ' ' + y + 'px');
            y--;
        }, 150);

Live example http://codepen.io/anon/pen/emMxXa

But it is rather 'jittery'. How can I make something like this to run more smoothly and slowly.

user3221449
  • 71
  • 2
  • 10

3 Answers3

2

You want to use and look into CSS transitions and CSS animations for real smoothyness.

-webkit-animation: move 30s linear 0s infinite alternate;
-moz-animation: move 30s linear 0s infinite alternate;

@-webkit-keyframes move { 
  from { background-position: 0px 0px } to { background-position: 0px 400px }  
}

@-moz-keyframes move { 
  from { background-position: 0px 0px } to { background-position: 0px 400px }  
}

Demo: http://codepen.io/anon/pen/EaEMvy

jAndy
  • 231,737
  • 57
  • 305
  • 359
  • Thanks. I've also found this http://stackoverflow.com/questions/21087518/animate-css-background-position-with-smooth-results-sub-pixel-animation – user3221449 Feb 20 '15 at 15:41
1

Take a look at this jsFiddle.

You will see that by reducing the interval value from 150 to 30 it will be a lot smoother:

             window.setInterval(function() {
                banner.css("backgroundPosition", x + 'px' + ' ' + y + 'px');
                y--;
                //x--;

                //if you need to scroll image horizontally -
                // uncomment x and comment y

            }, 30);

You can lower it even more but the more you lower it, the faster it gets also.

Alin
  • 1,218
  • 5
  • 21
  • 47
1

have a look at https://developer.mozilla.org/en-US/docs/Web/API/window.requestAnimationFrame

(function($) {

        var x = 0;
        var y = 0;
        //cache a reference to the banner
        var banner = $("#banner");

        // set initial banner background position
        banner.css('backgroundPosition', x + 'px' + ' ' + y + 'px');

        // scroll up background position every 90 milliseconds
        function step() {
            banner.css("backgroundPosition", x + 'px' + ' ' + y + 'px');
            y--;
            //x--;

            //if you need to scroll image horizontally -
            // uncomment x and comment y
                    window.requestAnimationFrame(step)
        }

    window.requestAnimationFrame(step);

})(jQuery);
Joe Fitter
  • 1,309
  • 7
  • 11