问题
I created the following testpage: http://methodus.de/wp/
It gets the dominant colour of the images of each blog post and use them for animation when scrolling down the page. Unfortunately, the colour can't be calculated as long as the image isn't fully loaded (see the javascript alert). The animation doesn't work then. When I reload the page, the images where cached by the browser, and everything works like charme.
The relevant code is:
$('.bg').each(function(index) {
var url = $(this).data('background-image');
img = new Image();
img.src = url;
averageColours[url] = getAverageColourAsRGB(img);
$(this).css('background-image', 'url(' + url + ')');
});
$('.bg').waypoint(function() {
var url = $(this).data('background-image');
var colour = getPreloadedAverageColourAsRGB(url);
console.log(url + ' ' + colour.r + ',' + colour.g + ',' + colour.b);
$('body').data('bgColour', 'rgb(' + colour.r + ',' + colour.g + ',' + colour.b + ')');
$('body').animate({backgroundColor: $('body').data('bgColour')});
}, { offset: 0 });
How can I postpone the waypoint binding until the images where fully loaded?
回答1:
There are some hacky ways to do this using $.load, but at the moment the best approach that i've found is to use imagesloaded.
You could then do something like:
$('.my-content-class').imagesLoaded( function() {
// ... your code here
});
来源:https://stackoverflow.com/questions/20252540/preload-images-with-jquery-to-get-dominant-colour-of-image