Giacomo Balli profile picture
Giacomo Balli
Innovation consultant specializing in mobile strategy
Let's Chat

Add Adaptive color background


This code sample will allow you to add a smooth background gradient that takes into account the image itself when it does not fill the entire element.


function addAdaptiveBgColor(el) {
var imgs = el.querySelectorAll('li');
for (var i = 0; i < imgs.length; i++) {
getImgColors(imgs[i]);
}
}

function getImgColors(imgEl1) {
var blockSize = 5, // only visit every 5 pixels
defaultRGB = {
r: 0,
g: 0,
b: 0
}, // for non-supporting envs
canvas = document.createElement('canvas'),
context = canvas.getContext && canvas.getContext('2d'),
data, width, height,
i = -4,
length,
rgbTop = {
r: 0,
g: 0,
b: 0
},
rgbBottom = {
r: 0,
g: 0,
b: 0
},
count = 0;
if (!context) {
return;
}
var imgEl = new Image();
var theSrc = imgEl1.style.backgroundImage.replace('url(', '').replace(')', '');
imgEl.src = theSrc;
imgEl.onload = function () {
height = canvas.height = imgEl.naturalHeight || imgEl.offsetHeight || imgEl.height;
width = canvas.width = imgEl.naturalWidth || imgEl.offsetWidth || imgEl.width;
context.drawImage(imgEl, 0, 0);
topPixels = context.getImageData(0, 0, width, 3);
bottomPixels = context.getImageData(0, height - 3, width, 3);
length = 3 * width;
while ((i += blockSize * 4) < length) {
++count;
rgbTop.r += topPixels.data[i];
rgbTop.g += topPixels.data[i + 1];
rgbTop.b += topPixels.data[i + 2];
rgbBottom.r += bottomPixels.data[i];
rgbBottom.g += bottomPixels.data[i + 1];
rgbBottom.b += bottomPixels.data[i + 2];
}

// ~~ used to floor values
rgbTop.r = ~~(rgbTop.r / count);
rgbTop.g = ~~(rgbTop.g / count);
rgbTop.b = ~~(rgbTop.b / count);
rgbBottom.r = ~~(rgbBottom.r / count);
rgbBottom.g = ~~(rgbBottom.g / count);
rgbBottom.b = ~~(rgbBottom.b / count);
imgEl1.style.webkitTransition = 'all 1s';
imgEl1.style.backgroundSize = 'contain';
imgEl1.style.backgroundPosition = '50% 50%';
imgEl1.style.backgroundImage += ', linear-gradient(rgb(' + rgbTop.r + ',' + rgbTop.g + ',' + rgbTop.b + '),rgb(' + rgbBottom.r + ',' + rgbBottom.g + ',' + rgbBottom.b + '))';
};
}

Directions:

- create your HTML with image as background then call addAdaptiveBgColor(el)


Note:
This snippet is based on a slider that uses the ul li technique.
This snippet focuses on iOS development. Make sure to verify/adapt any vendor prefixes.

Back to main listing.

Published: Mon, 11 Jan 2016 02:51:30 +0000