How to change div color when scrolling gradient?

I have an image that has many gradient colors. It scrolls on the page. Therefore, when the color of the image stops in the center of the page, the value of the thumbnail color changes. How to do it?

I am not sure, so I only send jsfiddle with html and css.

JSFIDDLE

//code
#colors{

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

enter image description here

+4
source share
1 answer

Something like this should get the color and set it to a thumbnail while scrolling

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

+2
source

Source: https://habr.com/ru/post/1525609/


All Articles