Preload images with JQuery to get dominant colour of image

青春壹個敷衍的年華 提交于 2019-12-24 17:57:36

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!