Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
24
rated 0 times [  28] [ 4]  / answers: 1 / hits: 24827  / 11 Years ago, wed, june 19, 2013, 12:00:00

I am working on a product that outputs images from users and the image information is overlayed on top of the aforementioned images. As you might imagine, the images require different text colors due to lightness/darkness. Is there a way to achieve this with JavaScript?



EDIT: I found a similar question to mine and there was a solution given in a jsfiddle (http://jsfiddle.net/xLF38/818). I am using jQuery for my site though. How would I convert the vanilla JavaScript to jQuery?



var rgb = getAverageRGB(document.getElementById('i'));
document.body.style.backgroundColor = 'rgb(' + rgb.r + ',' + rgb.g + ',' + rgb.b + ')';

function getAverageRGB(imgEl) {

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,
rgb = {
r: 0,
g: 0,
b: 0
},
count = 0;

if (!context) {
return defaultRGB;
}

height = canvas.height = imgEl.naturalHeight || imgEl.offsetHeight || imgEl.height;
width = canvas.width = imgEl.naturalWidth || imgEl.offsetWidth || imgEl.width;

context.drawImage(imgEl, 0, 0);

try {
data = context.getImageData(0, 0, width, height);
} catch (e) {
/* security error, img on diff domain */
alert('x');
return defaultRGB;
}

length = data.data.length;

while ((i += blockSize * 4) < length) {
++count;
rgb.r += data.data[i];
rgb.g += data.data[i + 1];
rgb.b += data.data[i + 2];
}

// ~~ used to floor values
rgb.r = ~~ (rgb.r / count);
rgb.g = ~~ (rgb.g / count);
rgb.b = ~~ (rgb.b / count);

return rgb;

}

More From » image

 Answers
4

I finally found something to do precisely what I want it to do! Enter Brian Gonzalez's
jquery.adaptive-backgrounds.js. Check this out:



$parent.css({
// backgroundColor: data.color
color: data.color
});


I just commented out the backgroundColor rule and made a new one for color. For white text, a text-shadow like:



text-shadow: 0 0 1px rgba($black, 0.3); // using Sass


should be enough. Thank you to everyone for your answers!


[#77543] Tuesday, June 18, 2013, 11 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
tomas

Total Points: 165
Total Questions: 111
Total Answers: 103

Location: Maldives
Member since Tue, Dec 21, 2021
2 Years ago
tomas questions
Thu, Jan 27, 22, 00:00, 2 Years ago
Mon, May 10, 21, 00:00, 3 Years ago
Tue, Jan 5, 21, 00:00, 3 Years ago
;