Skip to content

Instantly share code, notes, and snippets.

@mikkoh
Created June 5, 2015 16:02
Show Gist options
  • Save mikkoh/f8752d979f904d9c8690 to your computer and use it in GitHub Desktop.
Save mikkoh/f8752d979f904d9c8690 to your computer and use it in GitHub Desktop.
Working with colors
var red = 0xFF; // 255
var green = 0x10; // 16
var blue = 0xCC; // 204
var alpha = 0xFF;
// 24 bit color (no alpha)
var color24 = red << 16 | green << 8 | blue;
// 32 bit color (alpha)
// note >>> 0 if this isn't done alpha overflows to negation bit
// and returned value is negative
// http://stackoverflow.com/questions/18034974/why-in-javascript-expression-255-24-is-a-negative-number
var color32 = ( alpha << 24 | red << 16 | green << 8 | blue ) >>> 0;
// getting string values from color values
console.log(color24.toString(16)); // ff10cc
console.log(color32.toString(16)); // ffff10cc
// breaking apart colors into components
color24 = 0x010203;
color32 = 0x01020304;
red = color24 >> 16 & 0xFF;
green = color24 >> 8 & 0xFF;
blue = color24 & 0xFF;
console.log(red.toString(16)); // 1
console.log(green.toString(16)); // 2
console.log(blue.toString(16)); // 3
alpha = color32 >> 24 & 0xFF;
red = color32 >> 16 & 0xFF;
green = color32 >> 8 & 0xFF;
blue = color32 & 0xFF;
console.log(alpha.toString(16)); // 1
console.log(red.toString(16)); // 2
console.log(green.toString(16)); // 3
console.log(blue.toString(16)); // 3
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment