user3754676
user3754676

Reputation: 321

setting font color by taking image average color

I have an interesting HTML5 project where i need to set the font color by taking out the average of background image. For example this is my background which has two textboxes textbox1 and textbox2.

Image

In order to get the color of textbox1 i need to calculate the average of the background image portion and then set the color. Similarly for textbox2 i need to calculate the average of its background image and then set the color .I can get the textbox positions but how can i calculate the average colors?I am very confused. Any recommendations of how can it be done using jquery or css?? .

Upvotes: 0

Views: 1235

Answers (1)

mertyildiran
mertyildiran

Reputation: 6613

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;

}

Usage:

var rgb = getAverageRGB(document.getElementById('image'));

Example:

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

Source: Get average color of image via Javascript

Upvotes: 1

Related Questions