2014-11-08 77 views
2

我有附接到所述主體標籤的固定的背景圖像,該圖像是2048像素由2048像素並且頂部的中心位置:移動的背景圖像隨機和順利

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

欲一些運動添加到背景,因此它平移整個圖像周圍,而觀衆在瀏覽網站

使用:https://github.com/brandonaaron/jquery-cssHooks/blob/master/bgpos.js正常化的背景位置屬性,我可以按如下動畫形象:

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

我想添加隨機移動,而不是在10秒內進入右下角。

使用設置的時間間隔我可以每隔10秒爲圖像製作動畫,但是如何確定背景位置百分比?當圖像移動它應該是相同的速度,只是隨機位置

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'); 
} 

編輯:提琴更好地描述了我想做的事:http://jsfiddle.net/97w7f3c8/4/

回答

5

它如何能做到只是一個例子。隨機方向由隨機角度選擇,則審查出該目標不出去的範圍從0到100(可以是不必要的)

$(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>

+0

+1古樸典雅。 – arao6 2014-11-08 05:14:46

+0

@ user3023421我做了一個小的校正,兩個座標的角度應該是一樣的,這樣速度就會不變。 – Cheery 2014-11-08 05:18:19

0

CSS3現在supports背景轉換本身,如下所示。 bgpos.js是不需要的。另外,根據我的經驗,這在移動設備上的表現要好得多—運動平穩而沒有顛簸。我認爲這是因爲原生CSS轉換允許硬件加速。

body { 
    background: url(../img/mypic.jpg); 
    background-repeat: no-repeat; 
    background-position: 50% 50%; 
    transition: 0s linear; 
    transition-property: background-position; 
} 

 

var defaultTime = 10000; 

var x1 = 50, y1 = 50, moveBackground = function() { 

    var x2 = Math.random() * 100; 
    var y2 = Math.random() * 100; 

    // pythagorean theorem 
    var distance = Math.sqrt(Math.pow(x1 - x2, 2)+ Math.pow(y1 - y2, 2)); 

    var time = defaultTime * (distance/100); 

    $('body').css({ 
     'transition-duration': time + 'ms', 
     'background-position': x2+'% '+y2+'%' 
    }); 

    x1 = x2; 
    y1 = y2; 

    setTimeout(moveBackground, time); 
}; 

moveBackground();