Skip to content

Instantly share code, notes, and snippets.

@viveknarang
Created January 3, 2018 09:33
Show Gist options
  • Save viveknarang/105b8a6392c585a5a79fa0d436451055 to your computer and use it in GitHub Desktop.
Save viveknarang/105b8a6392c585a5a79fa0d436451055 to your computer and use it in GitHub Desktop.
// Created by Vivek Narang, 1/3/2018 4:33 AM EST
// A JavaScript function that takes in two arguments (Hex color codes) and returns the average of those ...
function avgColor(c1, c2) {
// Extract the R/G/B parts from the first argument ...
var c111 = parseInt(c1.substr(4, 2), 16);
var c121 = parseInt(c1.substr(2, 2), 16);
var c131 = parseInt(c1.substr(0, 2), 16);
// Extract the R/G/B parts from the second argument ...
var c211 = parseInt(c2.substr(4, 2), 16);
var c221 = parseInt(c2.substr(2, 2), 16);
var c231 = parseInt(c2.substr(0, 2), 16);
// Returning the Hex string by combining the average values of the R/G/B components and converting them to HEX codes ...
return (Math.round((c111 + c211)/2)).toString(16) + (Math.round((c121 + c221)/2)).toString(16) + (Math.round((c131 + c231)/2)).toString(16);
}
// Test Run ...
window.alert(avgColor("000000","FFFFFF"));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment