๋ณธ๋ฌธ ๋ฐ”๋กœ๊ฐ€๊ธฐ
JavaScript/Vanilla JS

[๋ฐ”๋‹๋ผJS๋กœ ํฌ๋กฌ ์•ฑ ๋งŒ๋“ค๊ธฐ] Image Background

by ์ฝ”๋”ฉํ•˜๋Š” ๋ถ•์–ด 2021. 3. 3.
๋ฐ˜์‘ํ˜•

[์ถœ์ฒ˜-์œ ํŠœ๋ธŒ ๋…ธ๋งˆ๋“œ ์ฝ”๋” Nomad Coders]

https://youtu.be/aHlJqxLREcY

 

 

๋จผ์ € ์‚ฌ์šฉํ•  ์ด๋ฏธ์ง€๋ฅผ ๋‹ค์šด๋ฐ›๋Š”๋‹ค

https://unsplash.com/

 

Beautiful Free Images & Pictures | Unsplash

Beautiful, free images and photos that you can download and use for any project. Better than any royalty free or stock photos.

unsplash.com

 

 

 

-์ด๋ฏธ์ง€ ๋žœ๋ค์œผ๋กœ ๋ถˆ๋Ÿฌ์˜ค๊ธฐ

 

bg.js

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

const IMG_NUMBER = 3;

function paintImage(imgNumber){
    const image = new Image();
    image.src = `/images/${imgNumber + 1}.jpg`;
    body.appendChild(image);
}

function genRandom(){
    const number = Math.floor(Math.random() * IMG_NUMBER);
    return number;
}

function init(){
    const randomNumber = genRandom();
    paintImage(randomNumber);
}

init();

์ƒˆ๋กœ๊ณ ์นจํ•˜๋ฉด ์ด๋ฏธ์ง€๊ฐ€ ๋žœ๋ค์œผ๋กœ ๋ณ€๊ฒฝ๋œ๋‹ค

 

 

index.css

body {
    color: #34495e;
    background-color: #2c3e50;
}

.btn {
    cursor: pointer;
}

h1 {
    color: #34495e;
    transition: color 0.5s ease-in-out;
}

.clicked {
    color: #7f8c8d;
}

.form,
.greetings {
    display: none;
}

.showing {
    display: block;
}

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

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

 

 

bg.js

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

// ์ด๋ฏธ์ง€ ๊ฐฏ์ˆ˜๋ฅผ ๋ณ€์ˆ˜๋กœ ์„ค์ •ํ•ด๋†“์œผ๋ฉด ๋‚˜์ค‘์— ํ•จ์ˆ˜์—์„œ ์ˆ˜์ •ํ•  ํ•„์š” ์—†์ด
// ์—ฌ๊ธฐ์„œ ์ˆซ์ž ๋ฐ”๋กœ ์ˆ˜์ •ํ•˜๋ฉด ๋จ!
const IMG_NUMBER = 3;

function paintImage(imgNumber){
    // ์ด๋ฏธ์ง€ ๊ฐ์ฒด ์ƒ์„ฑ
    const image = new Image();
    image.src = `/images/${imgNumber + 1}.jpg`;
    //image ํƒœ๊ทธ์— bgImage๋ผ๋Š” class ์ถ”๊ฐ€
    image.classList.add('bgImage');
    //body์— image ํƒœ๊ทธ ์ถ”๊ฐ€
    //parentNode.prepend(tag) : ๋ถ€๋ชจ๋…ธ๋“œ์˜ first child ์•ž์— ์š”์†Œ ์ถ”๊ฐ€
    body.prepend(image);
}

function genRandom(){
    const number = Math.floor(Math.random() * IMG_NUMBER);
    return number;
}

function init(){
    //getRandom ์‹คํ–‰ํ•ด์„œ ๋žœ๋คํ•œ ์ด๋ฏธ์ง€๋ฒˆํ˜ธ๋ฅผ ์–ป๊ณ 
    const randomNumber = genRandom();
    //๊ทธ๊ฑธ paintImage ํ•จ์ˆ˜์— ๋„ฃ์–ด ํ•ด๋‹น ์ด๋ฏธ์ง€๋ฅผ ์ž‘์—…
    paintImage(randomNumber);
}

init();

๋ฐ˜์‘ํ˜•

๋Œ“๊ธ€