Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Buy a domain name - Register cheap domain names from $0.99 - Namecheap

Scalable Hosting That Grows With You

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Semrush - keyword research tool

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

39,955 questions

51,897 answers

573 users

How to find the average between RGB colors c1 and c2 in Node.js

2 Answers

0 votes
function rgbToHex(r, g, b) {
    return `#${r.toString(16).padStart(2, '0').toUpperCase()}${g.toString(16).padStart(2, '0').toUpperCase()}${b.toString(16).padStart(2, '0').toUpperCase()}`;
}

function averageColor(c1, c2) {
    const avgR = Math.floor((c1.r + c2.r) / 2);
    const avgG = Math.floor((c1.g + c2.g) / 2);
    const avgB = Math.floor((c1.b + c2.b) / 2);
    return rgbToHex(avgR, avgG, avgB);
}

const color1 = { r: 255, g: 100, b: 50 };
const color2 = { r: 50, g: 170, b: 200 };

console.log(`Average Color (hex): ${averageColor(color1, color2)}`);

// Optionally export for reuse
module.exports = { rgbToHex, averageColor };

 
     
/*
run:
     
Average Color (hex): #98877D
     
*/

 



answered Jun 18, 2025 by avibootz
edited Jun 18, 2025 by avibootz
0 votes
function averageHexColors(c1, c2) {
    let hexColor = "#";
    for (let i = 0; i < 3; i++) {
        const sub1 = c1.substring(1 + 2 * i, 3 + 2 * i);
        const sub2 = c2.substring(1 + 2 * i, 3 + 2 * i);

        const i1 = parseInt(sub1, 16);
        const i2 = parseInt(sub2, 16);
        const avg = Math.floor((i1 + i2) / 2);

        const hex = avg.toString(16).toUpperCase().padStart(2, '0');
        hexColor += hex;
    }
    return hexColor;
}

const c1 = "#FF6432"; // RGB(255, 100, 50)
const c2 = "#32AAC8"; // RGB(50, 170, 200)

const average = averageHexColors(c1, c2);
console.log(`Average Color (hex): ${average}`);


// Optionally export for reuse
module.exports = { averageHexColors };

 
     
/*
run:
     
Average Color (hex): #98877D
     
*/

 



answered Jun 18, 2025 by avibootz
...