자바스크립트: 색상 이름을 rgb 코드로 바꾸기.
예를 들어 "red"라고 입력하면 red의 rgb에 해당하는 [255, 0, 0]의 색상 정보를 반환하는 프로그램을 만들어 보겠습니다. 일반 색상명으로 입력했는데 나중에 투명도를 적용하기 위해 rgba 등으로 바꾸고 싶을 때 사용하면 좋을 것 같네요.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
function getRGB(colorStr) {
let el = document.createElement("div");
el.style["background-color"] = colorStr;
document.body.appendChild(el);
let style = window.getComputedStyle(el);
let color = style["backgroundColor"];
document.body.removeChild(el);
let colorArray = color.replace(/rgb\(/, "").replace(/\)/, "").split(",")
return colorArray;
}
"anTIquEwhITe" 이런식으로 입력하거나 "rgb(255, 0, 0)" 또는 “#FF0000"이라고 입력해도 정상적으로 값을 반환합니다.
출처: https://stackoverflow.com/questions/16808575/get-color-code-from-color-word 위 링크에서 Moritz Roessler 라는 사람의 답변이 제일 깔끔한 것 같습니다.
This post is licensed under
CC BY 4.0
by the author.