javascript

20. Momentum 만들기 8 - 배경이미지 랜덤출력

으누아빠 2020. 6. 30. 12:57
반응형

Image Background

  1. 배경을 랜덤이미지로 출력

키워드1. Math.random()

  • 0 이상 1 미만의 부동소숫점 의사 난수.
//두 값 사이의 난수 생성하기
function getRandomArbitrary(min, max) {
  return Math.random() * (max - min) + min; // min 보다 크거나 같으며, max 보다 작은값
}

//두 값 사이의 정수 난수 생성하기
function getRandomInt(min, max) {
  min = Math.ceil(min);
  max = Math.floor(max);
  return Math.floor(Math.random() * (max - min)) + min; //최댓값은 제외, 최솟값은 포함
}

//최댓값을 포함하는 정수 난수 생성하기
function getRandomIntInclusive(min, max) {
  min = Math.ceil(min);
  max = Math.floor(max);
  return Math.floor(Math.random() * (max - min + 1)) + min; //최댓값도 포함, 최솟값도 포함
}

전체코드

bg.js

'use strict';

const body = document.querySelector('body');

const IMG_NUMBER = 3;

function getRandom(min, max) {
    min = Math.ceil(min);
    max = Math.floor(max);
    return Math.floor(Math.random() * (max - min + 1)) + min; //최댓값도 포함, 최솟값도 포함
}

function displayImg(imgNumber) {
    const image = new Image();

    image.src = `images/${imgNumber}.jpg`;
    image.classList.add('bgImage');
    body.appendChild(image);
}

function init() {
    const number = getRandom(1, 3);
    displayImg(number);
}

init();

index.html

<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8" />
        <title>Something</title>
        <link rel="stylesheet" href="index.css" />
        <script defer src="clock.js"></script>
        <script defer src="greeting.js"></script>
        <script defer src="todo.js"></script>
        <script defer src="bg.js"></script>
    </head>
    <body>
        <div class="js-clock">
            <h1 class="js-title">00:00</h1>
        </div>
        <form class="js-form form">
            <input type="text" placeholder="What is your name?" />
        </form>
        <h4 class="js-greetings greetings"></h4>
        <form class="js-toDoForm">
            <input type="text" placeholder="Write a to do" />
        </form>
        <ul class="js-toDoList"></ul>
    </body>
</html>

index.ccss

body {
    background-color: #2c3e50;
}

.btn {
    cursor: pointer;
}
body {
    color: #34495e;
}

.clicked {
    color: #7f8c8d;
}

.form,
.greetings {
    display: none;
}

.showing {
    display: block;
}

@keyframes fadeIn {
    from {
        opacity: 0;
    }
    to {
        opacity: 1;
    }
}

.bgImage {
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    z-index: -1;
    animation: fadeIn 0.5s linear;
}