인터랙티브 웹 개발(mouse move, loop )

Dev_Go·2022년 6월 28일
0
post-thumbnail

mouse move


예제보기

마우스 위치에 따라 x값, y값이 화면에 나타나면서 조개가 마우스움직임에 따라 자연스럽게 움직이는 예제

html

  <div id="container">
    <h1></h1>
    <div class="cursor_item">
      <img src="./images/sea-1328939_640.png" alt="">
    </div>  
  </div>

CSS

    * { box-sizing: border-box; }
    body {
      padding: 0;
      margin: 0;
      position: relative;
      width: 100%;
      height: auto;
    }
    #container{
      position:fixed;
      right:0;
      bottom:0;
      height:auto;
      min-height:100%;
      width:auto;
      min-width:100%;
      z-index:-100;
      background-size:cover;
      background-image: url(./images/white-sand-beach-2252020_1920.jpg);             
    }            
    .cursor_item {
      position: absolute;
      width: 130px;
      top: 0;
      left: 0;
    }
    .cursor_item img {
      width: 100%;
    }
    h1 {
      color: #222;
      padding: 20px;
    }

JS

let cursor_item;
    let x = 0;
    let y = 0;
    let mx = 0;
    let my = 0;
    let speed = 0.08;

    window.onload = function() {
      // h1을 html에서 찾는다
      let h1 = document.getElementsByTagName("h1")[0];
      // class가 cursor_item인 요소를 html에서 찾는다
      cursor_item = document.getElementsByClassName("cursor_item")[0];
      // type이 mousemove인 이벤트를 실행한다.
      window.addEventListener('mousemove', mouseFunc, false);
	  // h1을 "x: " + x + " mx: " + mx + "<br>" + "y: " + y + " my: " 
      // 이렇게 수정한다.
      function mouseFunc(e){
        x = e.clientX;
        y = e.clientY;
        h1.innerHTML = "x: " + x + " mx: " + mx + "<br>" + "y: " + y + " my: " + my;
      }
      // loop()함수 실행
      loop();
    }

    function loop() {
      // 마우스가 자연스럽게 따라오게 하는 함수 공식
      mx += (x - mx) * speed;
      my += (y - my) * speed;
	  // transform = "translate("+ mx + "px, " + my + "px)";
      // css를 추가시켜 자연스러운 느낌 추가
      cursor_item.style.transform = "translate("+ mx + "px, " + my + "px)";
      // 브라우저에 애니메이션을 수행하고 싶다고 알리고 브라우저가 
      // 다시 그리기 전에 애니메이션을 업데이트하기 위해 지정된 함수를 호출하도록 요청
      window.requestAnimationFrame(loop)
    }
profile
프론트엔드 4년차

0개의 댓글