Skip to content

Instantly share code, notes, and snippets.

@mauriciomassaia
Last active September 24, 2019 06:50
Show Gist options
  • Save mauriciomassaia/dfc8250874cbed79b8fcc6bc76e82228 to your computer and use it in GitHub Desktop.
Save mauriciomassaia/dfc8250874cbed79b8fcc6bc76e82228 to your computer and use it in GitHub Desktop.
Color convertion
/**
* @param {Array} arr - [140, 255, 1]
* @returns {Array} [0.5490196078, 1, 0.003921568627]
*/
export function normalizeArray (arr, value) {
return arr.map(v => v / value)
}
/**
* @param {Number} colorNum 0xff00ff
* @return {String} '#ff00ff'
*/
export function colorNumToStr (colorNum) {
let c = colorNum.toString(16)
while (c.length < 6) c = `0${c}`
return `#${c}`
}
/**
* @param {String} strColor '#ff00ff'
* @returns {Number} 0xff00ff
*/
export function colorStrToNum (strColor) {
return parseInt(`0x${strColor.substring(1, strColor.length)}`, 16)
}
/**
* Convert array of [255, 255, 255] to [1, 1, 1]
*
* @param {Array} arr - [140, 255, 1]
* @returns {Array} [0.5490196078, 1, 0.003921568627]
*/
export function normalizeRGB (arr) {
return normalizeArray(arr, 255)
}
/**
* Convert rgb values to Hex Number
* @param {Number} r - 0 - 255
* @param {Number} g - 0 - 255
* @param {Number} b - 0 - 255
* @return {Number} - 0xffffff | 16777215
*/
export function rgbToHex (r, g, b) {
return (1 << 24) + (r << 16) + (g << 8) + b
}
/**
* Convert Hex value to RGB (0 to 255 values)
*
* @param {String|Number} value - Accepts `#ffffff` and 0xffffff
* @return {Array} - [255, 255, 255]
*/
export function hexToRgb (value) {
const v = typeof value === 'number' ? colorNumToStr(value) : value
var r = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(v)
return r ? [parseInt(r[1], 16), parseInt(r[2], 16), parseInt(r[3], 16)] : null
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment