조금씩 꾸준히 완성을 향해

[Nomad Coders -JS로 크롬앱 만들기] Random Quote, Image 본문

기타 언어/JavaScript

[Nomad Coders -JS로 크롬앱 만들기] Random Quote, Image

all_sound 2022. 8. 9. 23:01

랜덤으로 바뀌는 명언과 배경이미지를 구현해 보자. 

 

랜덤의 수를 가져오기 위해서는 Math라는 module을 살펴봐야 한다. 

Mathe는 JavaScript의 built-in object여러가지 수학적인 작업들을 함수로 제공한다. 

 

 

https://developer.mozilla.org/ko/docs/Web/JavaScript/Reference/Global_Objects/Math

 

Math - JavaScript | MDN

Math는 수학적인 상수와 함수를 위한 속성과 메서드를 가진 내장 객체입니다. 함수 객체가 아닙니다.

developer.mozilla.org

 

 

그 중, Math.random() 은  0~1 사이의 임의의 수를 제공한다.

 

이렇게 소수점이 길게 붙은 숫자를 지정된 범위의 수로 바꾸기 위해서는 곱하기를 이용하면 된다.

 

0~10사이의 임의의 수를 구하고 싶다면 *10을 한다.

 

 

그리고 이것을 또 정수로 바꾸는 방법이 있다. 

Math.round() : 반올림 

Math.ceil() : 올림

Math.floor() : 내림

 

세 개가 미묘하게 다 다르니, 곱한 숫자가 포함 되느냐 안되느냐 등 상황에 따라 잘 골라 써야 한다. 

 

 

이제 만들고 있는 앱으로 가보자.

배열에 담긴 명언들을 랜덤으로 화면에 표시하고자 한다. 

const quotes = [
    {
      quote: "The way to get started is to quit talking and begin doing.",
      author: "Walt Disney",
    }]; //나머지 9개 생략
  
  const quote = document.querySelector("#quote span:first-child");
  const author = document.querySelector("#quote span:last-child");
  const todaysQuote = quotes[Math.floor(Math.random() * quotes.length)];
  
  quote.innerText = todaysQuote.quote;
  author.innerText = todaysQuote.author;

 

quotes[Math.floor(Math.random() * quotes.length)]  

 

랜덤으로 가져오려는 숫자가 배열의 index이기 때문에 floor로 내림을 했다.  

 quotes[0], quotes[1] ~ quotes[quotes.length-1] 

요 범위 내에서 명언들이 랜덤으로 나오게 된다. 

 

 

 

 

이제 랜덤 배경화면 구현으로 가보자. 

미리 저장된 이미지들의 파일 이름을 배열로 만든 후, 마찬가지로 랜덤하게 index를 부여한다.  

const images = ["0.jpeg", "1.jpeg", "2.jpeg", "3.jpeg", "4.jpeg"];

const chosenImage = images[Math.floor(Math.random()*images.length)];

 

그리고 이 이미지를 html에 넣는 작업을 해야 한다.  

 

const bgImage = document.createElement("img");
bgImage.src = `img/${chosenImage}`;

createElement()를 사용하면 자바스크립트에서 새로운 태그를 생성할 수 있다. 

img 태그를 생성하고 소스에 이미지 주소를 넣는다.

 

 

생성한 태그를 콘솔에 출력해 보면 무사히 잘 뜨는 걸 확인할 수 있다. 

 

 

그런데 이렇게 생성한 img 태그는 자바스크립트에만 존재하고 아직 document에는 존재하지 않는다.

img태그를 body 내부에 추가해야 비로소 화면에 나타나게 된다. 

 

const images = ["0.jpeg", "1.jpeg", "2.jpeg", "3.jpeg", "4.jpeg"];

const chosenImage = images[Math.floor(Math.random()*images.length)];

const bgImage = document.createElement("img");

bgImage.src = `img/${chosenImage}`;

document.body.appendChild(bgImage);

이렇게 appendChild()로 태그를 html에 연결하면,

 

 

 

 

태그도 body 안에 잘 들어와 있고, 화면에도 잘 나타나게 된다!!!