Skip to content

Conversation

datalater
Copy link
Collaborator

TIL

랜덤 색상값 추출 방법 변경

이전:

  • 10진수 rgba 사용
  • rbga의 개별 값을 모두 랜덤으로 추출
const randomColorValue = () => Math.floor(Math.random() * 256);

const randomColor = () => `rgba(${randomColorValue()}, ${randomColorValue()}, ${randomColorValue()}`;

변경:

  • 16진수 hex color 사용
  • 전체 값(256**3)에서 한번에 랜덤으로 추출
const randomHexColor = () => `#${Math.floor(Math.random() * (256 ** 3)).toString(16)}`;

@datalater datalater changed the base branch from main to JSmini_datalater September 7, 2021 13:48

const $button = document.getElementById('button');

const randomHexColor = () => `#${Math.floor(Math.random() * (256 ** 3)).toString(16)}`;
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

256**3(16 ** 6) 으로도 6자리수의 16진수값을 생성할수 있겠네요! 저는 2번 프로젝트에서도 동일하게 r,g,b를 따로 처리했었습니다.

Copy link
Collaborator Author

@datalater datalater Sep 14, 2021

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

넵 이번에는 rgb를 합친 전체 색상에 차례대로 인덱스를 붙인다고 생각하고 랜덤으로 인덱스를 선택하는 방식으로 처리해보았습니다ㅎㅎ

index color
0 #000000
1 #000001
... #...
256 ** 3 -1 #ffffff

그런데 지금 보니 이게 # 뒤에 16진수 값이 6자리가 안 만들어질 수도 있겠네요!!!! 수정해서 반영하겠습니다.

Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Copy link
Collaborator Author

@datalater datalater Sep 14, 2021

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

제 예상과 다른 값이 발생하네요.

저는 256**3 = 16777216에 Math.random()을 곱하면 Math.random()의 최대값은 1미만이니까 절대 16777216은 안 나올줄 알았는데 아래와 같은 예외 케이스가 발생하네요

예외 케이스:

Math.floor(16777216 * 0.99999999999999999).toString(16)
// '1000000'

일단 원인을 좀 더 알아보고 코드를 수정하도록 하겠습니다.

setInterval(() => {
$guideMessage.classList.toggle('change-color');
$currentStyle.classList.toggle('change-color');
}, 2000);
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

애니메이션이 아니더라도 setInterval과 transition으로 애니메이션과 같은 효과를 줄수 있군요! 한가지 또 배워갑니다 ㅎ

Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

오 애니메이션으로 하셨군요? 참고하러 보러가겠습니다 😀

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants