-
-
Save black-black-cat/bc6a89f8d5e6a1bc259a9c8160843677 to your computer and use it in GitHub Desktop.
rgb to hex, hex to rgb
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 rgbToHex = (text) => { | |
let arr = text.split(/[^0-9.]+/).slice(1, -1) | |
let r = +arr[0] | |
let g = +arr[1] | |
let b = +arr[2] | |
let a = +arr[3] | |
let v = (r << 16) + (g << 8) + b | |
let hex = ('00000' + v.toString(16)).slice(-6) | |
return a == null ? hex : {hex, a} | |
} | |
const hexToRgb = (text) => { | |
if (text.length === 3 || text.length === 4) { | |
text = text.split('').map(char => char + char).join('') | |
} | |
let hexA = '' | |
let a = 1 | |
let isRgba = text.length === 8 | |
if (isRgba) { | |
hexA = text.slice(-2) | |
a = parseInt(hexA, 16) / 0xff | |
text = text.slice(0, 6) | |
} | |
let v = parseInt(text, 16) // base 10 | |
let r = v & 0xff0000 >>> 16 | |
let g = v & 0x00ff00 >>> 8 | |
let b = v & 0x0000ff | |
if (isRgba) { | |
return `rgba(${[r, g, b, a].join(', ')})` | |
} | |
return `rgb(${[r, g, b].join(', ')})` | |
} | |
let rgb = 'rgb(200, 200, 200)' | |
// console.log(rgbToHex(rgb)) | |
// console.log(hexToRgb(rgbToHex(rgb)) === rgb) | |
// console.log(hexToRgb('c8c8c8ee')) | |
// console.log(hexToRgb('333')) | |
console.log(hexToRgb('3333')) |
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
<!doctype html> | |
<html lang="en"> | |
<head> | |
<meta charset="utf-8"> | |
<title>GistRun</title> | |
<link rel="stylesheet" href="styles.css"> | |
</head> | |
<body> | |
<h1>Hello world!</h1> | |
<script src="a.js"></script> | |
</body> | |
</html> |
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
/* todo: add styles */ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment