Search
 
SCRIPT & CODE EXAMPLE
 

JAVASCRIPT

identify primary colors in img with js

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 */
        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;

}
Comment

PREVIOUS NEXT
Code Example
Javascript :: express reload page after post 
Javascript :: JavaScript Finding HTML Element by Id 
Javascript :: fetch from vscode 
Javascript :: localecompare javascript 
Javascript :: slice string js 
Javascript :: refresh div after ajax success 
Javascript :: get index in map javascript 
Javascript :: ejs current year 
Javascript :: find element by object field vuejs 
Javascript :: js add multiple element to document 
Javascript :: prevent redirect javascript 
Javascript :: async function syntax 
Javascript :: Comment intégrer font awesome et bootstrap dans angular 13 
Javascript :: mongoose-encryption 
Javascript :: check fpr multiple values in an array jquery 
Javascript :: get the value of an input nativscript 
Javascript :: javascript ES6 Default Parameter Values 
Javascript :: xlsx to json using xlsx react 
Javascript :: local storage react 
Javascript :: compare objects 
Javascript :: bcrypt 
Javascript :: c# beautify json string 
Javascript :: javascript loop over three-dimensional array 
Javascript :: using apis in javascript 
Javascript :: acheck angular version 
Javascript :: Material-ui bank icon 
Javascript :: javascript es6 class 
Javascript :: Comparing and Filtering two arrays 
Javascript :: why we need react js 
Javascript :: how to enable emit on react in vs code 
ADD CONTENT
Topic
Content
Source link
Name
2+5 =