如何在滚动渐变时更改div颜色?

时间:2014-02-06 12:37:40

标签: javascript jquery html html5 css3

我的图像有很多渐变色。它在页面中向下滚动。因此,如果图像颜色在页面中心停止,则会更改缩略图颜色值。怎么做?

我不确定所以我只发布jsfiddle只有html和css。

JSFIDDLE

//code
#colors{

    width:123px;
    height:1360px ;
    background-image:url('http://s26.postimg.org/p4x2on37t/bgimage.jpg');
}

enter image description here

1 个答案:

答案 0 :(得分:2)

这样的东西应该得到颜色并在滚动时将其设置为缩略图

var bg = $('#colors').css('background-image').replace(/(url\(|\)|\")/g,'');
var img = new Image();
img.onload = function() {
    console.log('loaded')
    var canvas = $('<canvas />').get(0);
    canvas.width = img.width;
    canvas.height = img.height;
    var ctx = canvas.getContext('2d');
    ctx.drawImage(img, 0, 0, img.width, img.height);

    $('#wrapper').on('scroll', function() {
        console.log('test')
        var top       = $(this).scrollTop();
        var height    = $(this).outerHeight();
        var x         = (height / 2) + top;
        var pixelData = canvas.getContext('2d').getImageData(10, x, 1, 1).data;
        console.log(pixelData)

        $('#preview').css('background', 'rgb('+pixelData[0]+', '+pixelData[1]+', '+pixelData[2]+')')
    }).trigger('scroll');
}
img.src = bg;
if (img.complete) img.onload();

FIDDLE