Guest User

Compare Two HEX Colors in Javascript

a guest
Jan 18th, 2011
118
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. function areColorsSimilar(hexColor1, hexColor2)
  2. {
  3.    // convert from hex to rgb array
  4.    var col1 = new Array();
  5.    var col2 = new Array();
  6.    col1['r'] = HexToR(hexColor1);
  7.    col1['g'] = HexToG(hexColor1);
  8.    col1['b'] = HexToB(hexColor1);
  9.    col2['r'] = HexToR(hexColor2);
  10.    col2['g'] = HexToG(hexColor2);
  11.    col2['b'] = HexToB(hexColor2);
  12.  
  13.    brightness1 = parseInt((parseInt(col1['r']*299,10) + parseInt(col1['g']*587,10) + parseInt(col1['b']*114,10))/1000,10);
  14.    brightness2 = parseInt((parseInt(col2['r']*299,10) + parseInt(col2['g']*587,10) + parseInt(col2['b']*114,10))/1000,10);
  15.    brightnessRange = Math.max(brightness1,brightness2) - Math.min(brightness1,brightness2);
  16.  
  17.    
  18.    // get color difference
  19.    diffRed = Math.max(col1['r'],col2['r']) - Math.min(col1['r'],col2['r']);
  20.    diffGreen = Math.max(col1['g'],col2['g']) - Math.min(col1['g'],col2['g']);
  21.    diffBlue = Math.max(col1['b'],col2['b']) - Math.min(col1['b'],col2['b']);
  22.  
  23.    colorDifference = parseInt(diffRed + diffGreen + diffBlue,10);
  24.  
  25.    if(brightnessRange <= 125 && colorDifference <= 500)
  26.       return true;
  27.    
  28.  
  29.    return false;
  30.  
  31.  
  32. }
  33.  
  34. function HexToR(h) {return parseInt((cutHex(h)).substring(0,2),16)}
  35. function HexToG(h) {return parseInt((cutHex(h)).substring(2,4),16)}
  36. function HexToB(h) {return parseInt((cutHex(h)).substring(4,6),16)}
  37. function cutHex(h) {return (h.charAt(0)=="#") ? h.substring(1,7):h}
Advertisement
Add Comment
Please, Sign In to add comment