Created
October 28, 2019 16:40
-
-
Save zmnv/1c612e8a47ead14fc6caf0355a9f319a to your computer and use it in GitHub Desktop.
Continuous RGBA to HEXA converter
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const readline = require('readline'); | |
function colorToHex(rgb) { | |
let hex = Number(rgb).toString(16); | |
if (hex.length < 2) { | |
hex = `0${hex}`; | |
} | |
return hex; | |
}; | |
function alphaToHex(alpha) { | |
const preHex = Math.round(alpha * 255); | |
const hex = (preHex + 0x10000).toString(16).substr(-2).toUpperCase(); | |
return hex; | |
} | |
function rgbaToHex(r, g, b, a) { | |
const red = colorToHex(r); | |
const green = colorToHex(g); | |
const blue = colorToHex(b); | |
if (a === '1' || a === '0') { | |
return red + green + blue; | |
} | |
const alpha = alphaToHex(a); | |
return red + green + blue + alpha; | |
} | |
const rl = readline.createInterface({ | |
input: process.stdin, | |
output: process.stdout | |
}); | |
function askToConvert() { | |
rl.question('RGBA: ', (answer) => { | |
if (answer === 'exit') rl.close(); | |
const withoutSpaces = answer.replace(/\s/g, '').replace(/rgba\(/g, '').replace(/\)/g, ''); | |
const prepared = withoutSpaces.split(','); | |
const [r, g, b, a] = prepared; | |
const hex = rgbaToHex(r, g, b, a); | |
console.log(`#${hex}`); | |
askToConvert(); | |
}); | |
} | |
askToConvert(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment