Skip to content

Instantly share code, notes, and snippets.

@nola
Created October 14, 2013 15:18
Show Gist options
  • Select an option

  • Save nola/6977292 to your computer and use it in GitHub Desktop.

Select an option

Save nola/6977292 to your computer and use it in GitHub Desktop.
Scrolling background
.fullWH{
width: 100%;
height: 323px;
}
#bg1 {
background-image: url( "../img/bg1.png" );
}
#bg2 {
background-image: url( "../img/bg2.png" );
}
#bg3 {
background-image: url( "../img/bg3.png" );
}
<div id="bg1" class="fullWH"><!-- bg1 -->
<div id="bg2" class="fullWH"><!-- bg2 -->
<div id="bg3" class="fullWH"><!-- bg3 -->
</div><!-- bg3 -->
</div><!-- bg2 -->
</div><!-- bg1 -->
function polyfillRequestAnimFrame (window) {
var lastTime = 0;
var vendors = ['ms', 'moz', 'webkit', 'o'];
for(var x = 0; x < vendors.length && !window.requestAnimationFrame; ++x) {
window.requestAnimationFrame = window[vendors[x]+'RequestAnimationFrame'];
window.cancelAnimationFrame =
window[vendors[x]+'CancelAnimationFrame'] || window[vendors[x]+'CancelRequestAnimationFrame'];
}
if (!window.requestAnimationFrame) {
window.requestAnimationFrame = function(callback, element) {
var currTime = new Date().getTime();
var timeToCall = Math.max(0, 16 - (currTime - lastTime));
var id = window.setTimeout(function() { callback(currTime + timeToCall); }, timeToCall);
lastTime = currTime + timeToCall;
return id;
}
}
if (!window.cancelAnimationFrame) {
window.cancelAnimationFrame = function(id) {
clearTimeout(id);
}
}
}
$(function () {
var pausebg = false;
$("body").on("touchstart", function(){
pausebg = true;
});
$("body").on("touchend", function(){
pausebg = false;
});
polyfillRequestAnimFrame(window);
var xf = 40;
var xh = xf/4;
var xm = xf/4;
var yf = 20;
var yh = yf/2;
var ym = yf/4;
var xmod = 2; //Increase to slow down X
var ymod = 2; //Increase to slow down Y
var xmin = 0.3; //Increase to slow down X
var ymin = 0; //Increase to slow down Y
var bgs = [
{
ele: document.getElementById("bg1"),
pos: { x: Math.round(Math.random()*1000), y: Math.round(Math.random()*1000) },
mods: { x: 30, y: 0 }
},
{
ele: document.getElementById("bg2"),
pos: { x: Math.round(Math.random()*1000), y: Math.round(Math.random()*1000) },
mods: { x: 15, y: 0 }
} ,
{
ele: document.getElementById("bg3"),
pos: { x: Math.round(Math.random()*1000), y: Math.round(Math.random()*1000) },
mods: { x: -5, y: 0 }
}
];
function setBGPercent ( bgObj ) {
var mx = bgObj.mods.x/xmod;
var my = bgObj.mods.y/ymod;
bgObj.pos.x = bgObj.pos.x+(mx);
bgObj.pos.y = bgObj.pos.y+(my);
bgObj.pos.x = bgObj.pos.x%2000;
bgObj.ele.style.backgroundPosition = bgObj.pos.x+"px " + bgObj.pos.y + "px";
}
function animateBGS () {
for ( var bg in bgs ) {
setBGPercent( bgs[bg] );
}
window.requestAnimationFrame(animateBGS);
}
animateBGS();
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment