user3023421 user3023421 - 4 months ago 19
jQuery Question

Moving a background image randomly and smoothly

I have a fixed background image attached to the body tag, the image is 2048px by 2048px and is top centered:

body {
background: url(images/background.jpg) 50% 0% no-repeat fixed;
}


I want to add some movement to the background so it pans around the entire image while the viewers are navigating the site

Using: https://github.com/brandonaaron/jquery-cssHooks/blob/master/bgpos.js to normalize the background-position property, I can animate the image as follows:

$('body').animate({
backgroundPositionX: '100%',
backgroundPositionY: '100%'
}, 10000, 'linear');


Instead of going to the bottom right in 10 seconds, I want to add random movement.

Using set interval I can can animate the image every 10 seconds, but how do I determine the background position percentages? When the image moves it should be the same speed, just random locations

var currX = 50;
var currY = 0;

$(function () {
animate();

window.setInterval(animate(), 10000);
});

function animate() {
var newPosX = currX - (Math.random() * 50);
var newPosY = currY - (Math.random() * 50);

$('body').animate({
backgroundPositionX: newPosX + '%',
backgroundPositionY: newPosY + '%'
}, 10000, 'linear');
}


EDIT: a fiddle to better describe what I want to do: http://jsfiddle.net/97w7f3c8/4/

Answer

Just an example of how it could be done. Random direction is selected by random angle, then checkup that destination does not go out of range from 0 to 100 (may be not necessary)

$(function() {
     var p = [0, 0], speed = 10, runMe = function () {
        var angle = Math.random() * 2 * Math.PI;
        var d = [
            speed * Math.cos(angle), 
            speed * Math.sin(angle)
        ];

        for (var i = 0; i < 2; i++)
           p[i] = (p[i] + d[i] > 100 || p[i] + d[i] < 0) ? p[i] - d[i] : p[i] + d[i];

        $('body').animate({
            backgroundPositionX: p[0] + '%',
            backgroundPositionY: p[1] + '%'
        }, 5000, 'linear', runMe);
     };
    
     runMe();
});
body {
 background: url(http://www.psdgraphics.com/file/colorful-triangles-background.jpg);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js">
</script>
<script src="https://github.com/brandonaaron/jquery-cssHooks/blob/master/bgpos.js">
</script>