Skip to content

Instantly share code, notes, and snippets.

@gerbenvandijk
Created November 19, 2013 10:09
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save gerbenvandijk/7543149 to your computer and use it in GitHub Desktop.
Save gerbenvandijk/7543149 to your computer and use it in GitHub Desktop.
RGB to HEX
// Function to convert RGB Color to hex
function rgbToHex(r, g, b) {
if (r > 255 || g > 255 || b > 255)
throw "Invalid color component";
return ((r << 16) | (g << 8) | b).toString(16);
}
// example usage
data = canvas.getContext('2d').getImageData(1, 1, 1, 1).data; // we get color data from a canvas element here
hex = "#" + ("000000" + rgbToHex(data[0], data[1], data[2])).slice(-6); // we convert it to a hex value using the above function
if(hex != '#ffffff') { // we check for a certain color
// action
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment