Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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