모든 16 진 형태 모듈 방식
주요 과제는 2018 년 현재 몇 가지 형태의 HEX가 있다는 것입니다. 6 자 전통 형식, 3 자 단축 형식, 알파를 포함하는 새로운 4 자 및 8 자 형식. 다음 함수는 모든 HEX 형식을 처리 할 수 있습니다.
const isValidHex = (hex) => /^#([A-Fa-f0-9]{3,4}){1,2}$/.test(hex)
const getChunksFromString = (st, chunkSize) => st.match(new RegExp(`.{${chunkSize}}`, "g"))
const convertHexUnitTo256 = (hexStr) => parseInt(hexStr.repeat(2 / hexStr.length), 16)
const getAlphafloat = (a, alpha) => {
if (typeof a !== "undefined") {return a / 255}
if ((typeof alpha != "number") || alpha <0 || alpha >1){
return 1
}
return alpha
}
export const hexToRGBA = (hex, alpha) => {
if (!isValidHex(hex)) {throw new Error("Invalid HEX")}
const chunkSize = Math.floor((hex.length - 1) / 3)
const hexArr = getChunksFromString(hex.slice(1), chunkSize)
const [r, g, b, a] = hexArr.map(convertHexUnitTo256)
return `rgba(${r}, ${g}, ${b}, ${getAlphafloat(a, alpha)})`
}
Alpha는 다음과 같은 방법으로 함수에 제공 될 수 있습니다.
- 4 또는 8 양식의 일부로 HEX.
- 0-1 사이의 두 번째 매개 변수로
산출
const c1 = "#f80"
const c2 = "#f808"
const c3 = "#0088ff"
const c4 = "#0088ff88"
const c5 = "#98736"
console.log(hexToRGBA(c1))
console.log(hexToRGBA(c2))
console.log(hexToRGBA(c3))
console.log(hexToRGBA(c4))
console.log(hexToRGBA(c5))
console.log(hexToRGBA(c1, 0.5))
console.log(hexToRGBA(c3, 0.5))