使用JQuery预加载图像以获取图像的主色 [英] Preload images with JQuery to get dominant colour of image

查看:84
本文介绍了使用JQuery预加载图像以获取图像的主色的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我创建了以下测试页: http://methodus.de/wp/

I created the following testpage: http://methodus.de/wp/

它获取每个博客文章图像的主要颜色,并在向下滚动页面时将其用作动画.不幸的是,只要图像未完全加载,就无法计算颜色(请参见javascript警报).动画不起作用.当我重新加载页面时,浏览器会缓存图像,并且所有内容都像魅惑一样工作.

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.

相关代码为:

    $('.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?

推荐答案

使用 $.load ,但目前我发现的最佳方法是使用图像加载.

然后您可以执行以下操作:

You could then do something like:

$('.my-content-class').imagesLoaded( function() {
  // ... your code here
});

这篇关于使用JQuery预加载图像以获取图像的主色的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆