JAVASCRIPT

마우스 이펙트 만들기 세번째 !

Kim do hyun 2023. 3. 21. 14:01
728x90
반응형

마우스 이펙트 03

마우스 이펙트에 대한 세번째 사이트입니다.

마우스를 움직이면 정해진 범위만큼 마우스를 따라다니며 

 

 

 

위 사이트를 HTML, CSS, JAVASCRIPT를 만들었고 아래는 코드들입니다.

 

 

 

 

HTML

<body class="img03 bg03 Nanum">
    <header id="header">
        <h1>Javascript Mouse Effect03</h1>
        <p>마우스 이펙트 - 마우스 따라다니기</p>
        <ul>
            <li><a href="mouseEffect01.html">1</a></li>
            <li><a href="mouseEffect02.html">2</a></li>
            <li class="active"><a href="mouseEffect03.html">3</a></li>
            <li><a href="mouseEffect04.html">4</a></li>
            <li><a href="mouseEffect05.html">5</a></li>
            <li><a href="mouseEffect06.html">6</a></li>
        </ul>
    </header>
    <!-- header -->
    <main id="main">
        <div class="mouse__wrap">
            <div class="mouse__cursor"></div>
            <div class="mouse__cursor2"></div>
            <div class="mouse__text">
                <p>Either <span>you decide</span> to stay in the shallow end of the pool, or you go out in the ocean.</p>
                <p>당신은 수영장의 구석에 머무를지 바다로 나갈지를 당신 <span>스스로 결정할 수 있다.</span></p>
            </div>
        </div>
    </main>
    <!-- main -->
    <footer id="footer">
        <a href="mailto:kshkmn0929@naver.com">kshkmn0929@naver.com</a>
    </footer>
    <!-- footer -->

 

CSS

<style>
    #header {
        z-index: 100;
    }
    .mouse__wrap {
        cursor: none;
    }
    .mouse__text {
        width: 100%;
        height: 100vh;
        overflow: hidden;
        display: flex;
        align-items: center;
        justify-content: center;
        flex-direction: column;
        position: relative;
        z-index: 10;
    }
    .mouse__text p {
        font-size: 2.2vw;
        line-height: 1.6;
    }
    .mouse__cursor {
        position: absolute;
        left: 0;
        top: 0;
        width: 200px;
        height: 200px;
        border-radius: 50%;
        border: 5px solid #fff;
        background-color: rgba(255, 255, 255, 0.5);
        background-image: url(img/mouseEffect03-min.jpg);
        background-size: cover;
        background-position: center center;
        background-attachment: fixed;
    }
</style>

 

JAVASCRIPT

<script src="https://cdnjs.cloudflare.com/ajax/libs/gsap/3.11.5/gsap.min.js"></script>
<script>
    // 선택자
    const cursor = document.querySelector(".mouse__cursor");


    // console.log(cursor.clientWidth);    //190
    // console.log(cursor.clientHeight);   //190
    // console.log(cursor.offsetWidth);    //200
    // console.log(cursor.offsetHeight);   //200

    console.log(cursor.getBoundingClientRect());

    const circle = cursor.getBoundingClientRect();

    const DOMRect = {
        bottom : 200,
        height : 200,
        left : 0 ,
        right : 200,
        top : 0,
        width : 200,
        x : 0,
        y : 0
    }

    // console.log(DOMRect.width);



    window.addEventListener("mousemove", e => {
        gsap.to(cursor, {
            duration: 0.5, 
            left: e.pageX - circle.width/2, 
            top: e.pageY - circle.height/2
        });
    });
</script>

 

 

코드 설명

const cursor = document.querySelector(".mouse__cursor");

        
// console.log(cursor.clientWidth);    //190
// console.log(cursor.clientHeight);   //190
// console.log(cursor.offsetWidth);    //200
// console.log(cursor.offsetHeight);   //200

console.log(cursor.getBoundingClientRect());

const circle = cursor.getBoundingClientRect();

const DOMRect = {
    bottom : 200,
    height : 200,
    left : 0 ,
    right : 200,
    top : 0,
    width : 200,
    x : 0,
    y : 0
}

이 코드는 먼저 querySelector() 함수를 사용하여 HTML 문서에서 class 속성이 mouse__cursor인 요소를 찾아서 cursor 변수에 할당합니다.

그리고 console.log() 함수를 사용하여 cursor.getBoundingClientRect() 메소드의 반환값을 콘솔에 출력합니다. 이 메소드는 요소의 크기와 위치 정보를 나타내는 DOMRect 객체를 반환합니다.

다음으로, const circle = cursor.getBoundingClientRect(); 코드를 사용하여 cursor 요소의 위치와 크기를 나타내는 DOMRect 객체를 circle 변수에 할당합니다.

마지막으로, DOMRect 객체를 생성하여 다양한 속성 값을 설정합니다. 이 객체는 DOMRect 인터페이스를 구현한 객체로, getBoundingClientRect() 메소드가 반환하는 객체와 비슷한 속성을 가지고 있습니다.

각 속성의 의미는 다음과 같습니다.

bottom: 요소의 아래쪽 가장자리의 y 좌표
height: 요소의 높이
left: 요소의 왼쪽 가장자리의 x 좌표
right: 요소의 오른쪽 가장자리의 x 좌표
top: 요소의 위쪽 가장자리의 y 좌표
width: 요소의 너비
x: 요소의 왼쪽 가장자리의 x 좌표
y: 요소의 위쪽 가장자리의 y 좌표
이렇게 생성된 DOMRect 객체는 원하는 위치와 크기 정보를 가지고 있어, 애니메이션 등에 사용될 수 있습니다.

 

window.addEventListener("mousemove", e => {
    gsap.to(cursor, {
        duration: 0.5, 
        left: e.pageX - circle.width/2, 
        top: e.pageY - circle.height/2
    });
});

window.addEventListener() 함수를 사용하여 "mousemove" 이벤트를 감지하고 있습니다. 이 이벤트는 마우스가 움직일 때마다 발생합니다.

그리고 gsap.to() 함수를 사용하여 gsap 라이브러리를 이용해 요소를 움직입니다. 이 함수는 첫번째 매개변수로 움직일 요소를 받고, 두번째 매개변수로 해당 요소의 움직임을 정의하는 객체를 받습니다.

객체 안에서는 duration 속성으로 애니메이션의 지속 시간을 설정하고, left와 top 속성으로 마우스 커서의 위치를 계산하여 요소의 위치를 변경합니다.

e.pageX와 e.pageY는 마우스 포인터의 현재 위치를 나타내는 속성입니다. circle.width와 circle.height는 이동할 요소의 너비와 높이를 나타냅니다. 따라서 left와 top 속성을 계산하여 요소를 마우스 커서의 위치에 따라 움직이게 됩니다.

여기서 left와 top 속성의 값에 circle.width/2와 circle.height/2를 빼는 이유는 마우스 커서가 cursor 요소의 중앙으로 위치하도록 하기 위함입니다.

따라서 마우스 커서의 움직임에 따라 cursor 요소가 부드럽게 따라 움직이게 됩니다.