java script 메모

[javascript] Math.random()과 .animate()

그나쓰 2022. 12. 22. 13:55

버튼을 누를때마다 랜덤한 위치에 랜덤한 사이즈의

심장처럼 콩딱콩딱 커졌다 작아졌다하는 박스를 만들거다

우선 html을 쏘 씜플하게

//html
<div class="wrap">
    <button type="button" class="add">+ add</button>
</div>
//css
* { margin: 0; padding: 0; box-sizing: border-box; line-height: 1; }
.wrap { padding: 20px; position: relative; width: 80vw; height: 80vh; }
.wrap div { position: absolute; transform: translate(-50%, -50%); text-align: right; cursor: pointer; }
.wrap > button { position: relative; z-index: 999; cursor: pointer; }

 

//js
const btn = document.querySelector(".add");
const wrap = document.querySelector(".wrap");

btn.addEventListener("click", () => {
    const x = Math.floor(Math.random() * 100),
          y = Math.floor(Math.random() * 100), // 0 ~ 100
          width = Math.floor(Math.random() * 300) + 50, // 50 ~ 300
          //정사각형 아니면 height값도 생성해주기
          duration = Math.random() * 3000 + 500; //0.5초 ~ 3초
    const box = document.createElement("div");

    box.style.left = x + "%";
    box.style.top = y + "%"; //랜덤 위치
    box.style.background = `url('https://picsum.photos/${
        width + 50
    }')no-repeat center / 100%`; //picsum에서 ${width}사이즈의 이미지 끌고오기

    box.style.width = width + "px";
    box.style.height = width + "px"; //랜덤 사이즈

    const animation = box.animate([
            { width: `${width + 50}px`, height: `${width + 50}px` },
            { width: `${width}px`, height: `${width}px` },
            { width: `${width + 50}px`, height: `${width + 50}px` }
    ], {
            duration: duration,
            iterations: Infinity
    });

    wrap.appendChild(box);

    const img = document.querySelectorAll(".wrap > div");
    img.forEach((e) => {
        e.addEventListener("click", () => {
            e.remove();
        });
    });
});

animate 자세하게 사용해 본 건 이번이 처음인듯,

https://developer.mozilla.org/en-US/docs/Web/API/Element/animate

 

Element.animate() - Web APIs | MDN

The Element interface's animate() method is a shortcut method which creates a new Animation, applies it to the element, then plays the animation. It returns the created Animation object instance.

developer.mozilla.org

https://hankong.tistory.com/42

 

[JAVASCRIPT] 자바스크립트로 css animation

계속 삽질하다가 겨우 해결한 자바스크립트로 css animation 실행하기와 더불어 css animation 관련된 내용을 정리해보려한다. 나는 tansform을 이용하여 아이콘이 위아래로 떨리는 모양을 만들고 싶었다

hankong.tistory.com

저렇게 사용하는구나.

라이브러리 개떡칠같은거 하지말고,

js로 만들어보쟈 ~ 잘 봐두자 ~

결과

https://cd0x8b.csb.app/

 

Static Template

 

cd0x8b.csb.app

 

회사에서 할 일 없을 때마다 공부하는 거 너무 재밌쨔나 ~

근데 내 키보드 소리 너무 시끄럽쨔나 ~

키보드 무소음으로 바꿔야 할 거 같쨔나 ~