JavaScript를 사용하여 모든 문자열을 임의의 색상으로 변환

Mar 24 2023
사용자 이름이나 제목과 같은 문자열을 기반으로 고유한 색상을 생성해야 했던 적이 있습니까? 프로젝트에서 태그의 고유한 표현을 만드는 것이 흥미로웠지만 각 태그에 색상을 할당할 수 없었습니다. JavaScript를 사용하면 쉽게 할 수 있습니다! 이 기사에서는 HSL 색상 공간을 사용하여 모든 문자열을 임의의 색상으로 변환하는 간단한 코드를 작성하는 방법을 보여줍니다.

사용자 이름이나 제목과 같은 문자열을 기반으로 고유한 색상을 생성해야 했던 적이 있습니까? 프로젝트에서 태그의 고유한 표현을 만드는 것이 흥미로웠지만 각 태그에 색상을 할당할 수 없었습니다. JavaScript를 사용하면 쉽게 할 수 있습니다! 이 기사에서는 HSL 색상 공간을 사용하여 모든 문자열을 임의의 색상으로 변환하는 간단한 코드를 작성하는 방법을 보여줍니다.

Unsplash에 있는 Keila Hötzel의 사진

우리가 사용할 코드는 두 가지 기능을 기반으로 합니다: getColorFromString.

코드는 다음과 같습니다.

function getColorFromString(string, saturation = 50, lightness = 75, defaultColor = '#000000') {
  // Check if the string is empty or null or has less then 3 characters
  if (!string) {
    return defaultColor;
  }
if (string.trim().length < 3) {
    return defaultColor;
  }
  
  // Calculate the hue value based on the first three characters of the string
  const hue = string.charCodeAt(0) * string.charCodeAt(1) * string.charCodeAt(2);

  // Convert the saturation and lightness values from percentages to decimals between 0 and 1
  const s = saturation / 100;
  const l = lightness / 100;

  // Calculate the alpha value
  const a = s * Math.min(l, 1 - l);

  // Calculate the red, green, and blue values
  const f = (n) => {
    const k = (n + hue / 30) % 12;
    const color = l - a * Math.max(Math.min(k - 3, 9 - k, 1), -1);
    return Math.round(255 * color).toString(16).padStart(2, '0');
  };

  // Return the hex color code
  const hexCode = `#${f(0)}${f(8)}${f(4)}`;
  return hexCode || defaultColor;
}

문자열과 몇 가지 선택적 매개 변수를 사용하고 해당 색상 코드를 16진수 문자열 형식으로 반환합니다.

다음은 함수가 수행하는 작업을 단계별로 보여줍니다.

  1. string인수가 null인지, 비어 있는지 또는 3자 미만인지 확인합니다 . 이러한 조건 중 하나라도 충족되면 (검은색) defaultColor값을 반환합니다 #000000.
  2. 해당 문자 코드를 함께 곱하여 인수 hue의 처음 세 문자를 기준으로 값을 계산합니다 .string
  3. saturation및 lightness값을 백분율에서 0과 1 사이의 십진수로 변환합니다 .
  4. 및 값을 alpha기준으로 값을 계산합니다 .saturationlightness
  5. f정수를 취하고 n해당 인덱스에 대한 빨간색, 녹색 또는 파란색 값을 계산하는 도우미 함수를 정의합니다 .
  6. 도우미 함수를 사용하여 f최종 색상 코드의 빨간색, 녹색 및 파란색 값을 계산합니다.
  7. 최종 색상 코드를 16진수 문자열로 반환합니다.

기능을 사용하는 방법은 다음과 같습니다.

const color = getColorFromString("hello world");
console.log(color); // Output: "#d2df9f"

그게 다야! 몇 줄의 코드만으로 모든 문자열을 고유한 색상으로 변환할 수 있습니다. 이는 아바타 색상 생성, 사용자 이름 강조 표시 등과 같은 다양한 응용 프로그램에서 유용할 수 있습니다.

getColorFromString특정 클래스 태그로 모든 구성 요소의 색상을 변경하는 기능을 사용하는 방법

<div class="colorize">item 1</div>
<div class="colorize">item 2</div>
<div class="colorize">item 3</div>
document.addEventListener("DOMContentLoaded", function() {
  const elements = document.querySelectorAll('.colorize');

  elements.forEach((el) => {
    const text = el.textContent.trim();
    const color = getColorFromString(text);

    el.style.backgroundColor = color;
    el.style.color = "#ffffff";
  });
});

document.querySelectorAll이 예제에서는 먼저 "colorize" 클래스를 사용하여 모든 요소를 ​​선택합니다. 그런 다음 메소드를 사용하여 각 요소를 반복 forEach하고 배경색을 getColorFromString요소의 텍스트 콘텐츠를 입력 문자열로 사용하여 함수에서 생성한 임의의 색상으로 설정합니다.