I'm currently working on a parallax website that consists of a sequence of around 400 images. The background images change dynamically as the user scrolls through the page, creating a smooth animation effect. While I have managed to implement the scrolling functionality, I am encountering issues with the transition between background images not being seamless. There is a brief moment where a blank space is visible, depending on the internet connection speed. Additionally, the images are not being cached, leading to a new image request every time. I'm seeking advice on how to optimize the code to ensure smooth animation transitions without requesting new images each time and utilizing cached images effectively. I also explored using canvas for the animation, but encountered similar issues with image requests upon scrolling. Here is my current code structure for standard background image changing based on page scroll:
HTML
<div class="container">
<div id="background-images" class="background-images">
<div class="test"></div>
</div>
</div>
CSS
#background-images{
height: 4000px;
}
.container{
border: 1px solid red;
height: 400px;
overflow: auto;
}
.test{
position: fixed;
top: 0;
left: 0;
z-index: 999;
width: 600px;
height: 600px;
}
Javascript
var $container = $(".container");
var $bgImage = $(".test");
// Attaching the scroll event to the background image
$container.scroll(function(event) {
var position = $container.scrollTop();
setBgImage(position);
});
// Preload the specified number of images for caching
function preload(totalImages) {
for (var i = 0; i < totalImages; i++) {
$('<img/>')[0].src = getImgUrl(i);
}
}
preload(36); // Preload 36 images to be cached
// Set the background image based on scroll position
function setBgImage(position){
var imageNum;
var lineCount = 0;
imageNum = parseInt(position / 100);
console.log("IMG: " + imageNum + ", Position: " + position);
$bgImage.css("background-image", "url('" + getImgUrl(imageNum) + "')");
}
// Get the URL for the placeholder background image
function getImgUrl(num){
return "http://placehold.it/200x200/&text=" + num;
}
JSFiddle: http://jsfiddle.net/4j9u8qtf/1/