TS 랜덤 rgb 색상 구하기

Khan·2022년 8월 4일
0
post-thumbnail
interface colorType {
  r: number;
  g: number;
  b: number;
}

//랜덤 color 구하기
const getRandomRGB = () => {
  const r = Math.floor(Math.random() * 256);
  const g = Math.floor(Math.random() * 256);
  const b = Math.floor(Math.random() * 256);
  return { r, g, b };
};

//유효한 RGB인지 체크
const isValidColorCode = (RGB: colorType) => RGBToString(RGB).length >= 7;

//유효한 RBG값만 반환
const getValidColorCode = (): colorType => {
  let RGB = getRandomRGB();
  while (!isValidColorCode(RGB)) RGB = getRandomRGB();
  return RGB;
};

//RGB값으로 colorCode 구하기
const numToHex = (num: number) => num.toString(16).toUpperCase();

//"#"붙어있는 colorCode 반환
const RGBToString = ({ r, g, b }: colorType): string =>
  `#${numToHex(r)}${numToHex(g)}${numToHex(b)}`;

//backgroundColor 구하기
export const getRandomLabelColor = (): string => {
  const randomColor = getValidColorCode();

  const backgroundColorCode = RGBToString(randomColor);

  return backgroundColorCode;
};
  1. 랜덤하게 0 ~ 255 사이의 숫자를 3개 구한다.
  2. 랜덤하게 구한 r, g, b를 16진수 값으로 변경시켜 주고 소문자로 나온 값을 대문자로 변경시켜준다.
  3. 16진수로 변경된 값을 #000000으로 반환시키고 문자열의 길이가 7이 넘을 때 까지 반복문을 돌린다.
  4. 유효한 랜덤의 RGB 값을 구하고 한 번 더 16진수로 변화 후 앞에 #을 붙인 후 반환해 준다.

0개의 댓글