Blinking Hello Kitty Angel

javascript

자바스크립트 마우스 이펙트 두 번째 총정리

xoouxa 2023. 3. 21. 13:17

“ 지연되는 프로젝트에 인력을 더 투입하면 오히려 더 늦어진다. ”

- Frederick Philips Brooks
Mythical Man-Month 저자
728x90

안녕하세요 ヾ(≧▽≦*)o 오늘은 자바스크립트 마우스 이펙트 두 번째 만드는 방법에 대해 총정리를 해보도록 하겠습니다.

자바스크립트 마우스 이펙트 첫 번째와 비슷하지만 다르게 구상하고 새로운 걸 추가해주었습니다.

(마우스 이펙트 첫 번째 바로가기 : https://xoouxa58.tistory.com/44)

 

reset CSS

마우스 이펙트 페이지를 10페이지를 만들어 줄건데

10페이지마다 폰트를 다르게 할 거라 각각 페이지별로 폰트를 지정해 줍니다.

저는 폰트어썸이라는 사이트에서 폰트를 다운받았습니다.

@import url('https://webfontworld.github.io/NexonLv1Gothic/NexonLv1Gothic.css');
@import url('https://webfontworld.github.io/miryang/MYArirangGothic.css');
@import url('https://webfontworld.github.io/woori/Wooridaum.css');
@import url('https://webfontworld.github.io/suseong/SuseongBatang.css');
@import url('https://webfontworld.github.io/knps/KNPSBandali.css');
@import url('https://webfontworld.github.io/NexonMabinogi/MabinogiClassic.css');
@import url('https://webfontworld.github.io/jeongseon/JSDongkang.css');
@import url('https://webfontworld.github.io/dgb/IMHyemin.css');
@import url('https://webfontworld.github.io/Cafe24Ssukssuk/Cafe24Ssukssuk.css');
@import url('https://webfontworld.github.io/seoulhangang/SeoulHangangC.css');
/* reset */
* {
    margin: 0;
    padding: 0;
}
*, *::before, *::after {
    box-sizing: border-box;
}
a {
    text-decoration: none;
    color: #222;
}
h1, h2, h3, h4, h5, h6 {
    font-weight: normal;
}
li, ul, ol {
    list-style: none;
}
img {
    vertical-align: top;
    width: 100%;
}
em {
    font-style: normal;
}
.font01 {
    font-family: 'NexonLv1Gothic';
    font-weight: 300px;
}
.font02 {
    font-family: 'MYArirangGothic';
    font-weight: 300px;
}
.font03 {
    font-family: 'Wooridaum';
    font-weight: 300px;
}
.font04 {
    font-family: 'SuseongBatang';
    font-weight: 300px;
}
.font05 {
    font-family: 'KNPSBandali';
    font-weight: 300px;
}
.font06 {
    font-family: 'MabinogiClassic';
    font-weight: 300px;
}
.font07 {
    font-family: 'JSDongkang';
    font-weight: 300px;
}
.font08 {
    font-family: 'IMHyemin';
    font-weight: 300px;
}
.font09 {
    font-family: 'Cafe24Ssukssuk';
    font-weight: 300px;
}
.font10 {
    font-family: 'SeoulHangangC';
    font-weight: 300px;
}

 

mouse css

다음은 마우스 css를 만들어줍니다.

body {
    width: 100%;
    overflow: hidden;
    height: 100vh;
    background-position: center center;
    background-size: cover;
}
body.img01{
    background-image: url(../img/mouseEffect01-1.jpg);
}
body.img02{
    background-image: url(../img/mouseEffect02-1.jpg);
}
body.img03{
    background-image: url(../img/mouseEffect03-min.jpg);
}
body.img04{
    background-image: url(../img/mouseEffect04-min.jpg);
}
body.img05{
    background-image: url(../img/mouseEffect05-min.jpg);
}
body.img06{
    background-image: url(../img/mouseEffect06-min.jpg);
}
body.img07{
    background-image: url(../img/mouseEffect07-min.jpg);
}
body.img08{
    background-image: url(../img/mouseEffect08-min.jpg);
}
body.img09{
    background-image: url(../img/mouseEffect09-min.jpg);
}
body .img10{
    background-image: url(../img/mouseEffect10-min.jpg);
}
body::after {
    content: '';
    position: absolute;
    left: 0; top:0;
    width: 100%;
    height: 100vh;
    z-index: -1;
}
body.bg01::after {
    background: rgba(245, 219, 188, 0.401);
}
body.bg02::after {
    background: rgba(186, 235, 195, 0.353);
}
body.bg03::after {
    background: rgba(158, 99, 99, 0.87);
}
body.bg04::after {
    background: rgba(224, 174, 174, 0.87);
}
body.bg05::after {
    background: rgba(250, 226, 226, 0.87);
}
body.bg06::after {
    background: rgba(83, 88, 20, 0.87);
}
body.bg07::after {
    background: rgba(177, 175, 72, 0.87);
}
body.bg08::after {
    background: rgba(181, 186, 96, 0.87);
}
body.bg09::after {
    background: rgba(231, 240, 150, 0.87);
}
body.bg10::after {
    background: rgba(237, 255, 217, 0.87);
}

/* header */
#header {
    padding: 20px;
    position: absolute;
    left: 0;
    top:0;
}
#header h1 {
    margin-bottom: 10px;
}
#header p {
    margin-bottom: 10px;
}
#header a {
    color: #fff;
}
#header li {
    display: inline-block;
}
#header li a {
    border: 1px solid #fff;
    width: 30px;
    height: 30px;
    display: inline-block;
    color: #fff;
}
#header li.active a {
    background-color: #fff;
    color: #000;
}

/* footer */
#footer {
    position: absolute;
    right: 0;
    bottom: 0;
    padding: 20px;
}
#footer a {
    color: #fff;
}

내가 원하는 이미지를 저장해온 뒤 body에 페이지별로 보이고 싶은 이미지를 각각 저장시켜줍니다.

각각 페이지별로 이미지와 어울리는 색상을 지정해 페이지를 열었을 때 이미지와 어울리는 배경을 설정해 줍니다.

앞으로 사용할 이미지나 폰트는 calss로 지정해 주었기 때문에 뒤에 이름을 붙여 불러와 줍니다.

 

HTML

<body class="img02 bg02 font02">
    <header id="header">
        <h1>Javascript mouseEffect02</h1>
        <p>마우스 이펙트 - 마우스 따라다니기</p>
        <ul>
            <li><a href="mouseEffect01.html">1</a></li>
            <li class="active"><a href="mouseEffect02.html">2</a></li>
            <li><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>We <span>need to protect</span> the environment and treat it with care.</p>
                <p>환경을 <span>보호하고</span> 소중히 다뤄야 합니다.</p>
            </div>

    </main>
    <!--main-->
    <footer id="footer">
        <a href="mailto:yuna243441@naver.com">yuna243441@naver.com</a>
    </footer>
    <!--footer-->

배경에 사진을 넣고, 그 위에 내가 넣고 싶은 문구를 지정해 한국어와 영어로 각각 지정해준 뒤

마우스 따라다니기 효과를 넣어주고 span 처리를 해준 문구 위에 마우스효과를 주도록 하겠습니다.

 

애니메이션 효과 설정해주기

<style>
        .mouse__wrap {
            cursor: none;
        }
        .mouse__text {
            width: 100%;
            height: 100vh;
            display: flex;
            align-items: center;
            justify-content: center;
            flex-direction: column;
            overflow: hidden;
        }
        .mouse__text p {
            font-size: 2vw;
            line-height: 1.9;
        }
        .mouse__text p:last-child {
            font-size: 3vw;
        }
        .mouse__text p span{
            color:#fff
        }
        .mouse__cursor {
            position: absolute;
            left: 0;
            top:0;
            width: 10px;
            height: 10px;
            z-index: 9999;
            border-radius: 50%;
            background-color: rgba(0, 0, 0, 0.722);
            user-select: none;
            pointer-events: none;
            transition: transform 0.3s;
        }
        .mouse__cursor2 {
            position: absolute;
            left: 0;
            top:0;
            width: 30px;
            height: 30px;
            z-index: 9998;
            border-radius: 50%;
            background-color: rgba(255, 255, 255, 0.521);
            user-select: none;
            pointer-events: none;
            transition: transform 0.3s;
        }
        .mouse__cursor.active {
            transform: scale(0);
        }
        .mouse__cursor2.active {
            transform: scale(5);
            background-color: rgba(111, 178, 110, 0.3);
        }
    </style>

배경색과 어울리는 마우스 커서 모양과 배경을 조금 가려줄 수 있는 배경 컬러를 지정해 줍니다.

내가 지정한 영어 문구와 한글 문구의 크기를 조절해 줍니다.

mouse__wrap안에 커서를 none으로 지정해 줘야 기존의 커서는 화면에서 보이지 않게 됩니다.

헤더에 있는 네모칸과 푸터에 있는 메일주소에도 마우스 오버 효과 주기

이번엔 다른 페이지와 다르게 헤더와 푸터에도 span처리를 한 것과 같은 동일한 효과를 넣어주도록 하겠습니다.

하지만 이번엔 헤더와 푸터에 span을 주지 않고 작업해주도록 하겠습니다.

const cursor3 = document.querySelector("#header ul li.active");
const cursor4 = document.querySelector("#footer a");

선택자에 헤더와 푸터를 넣어줍니다.

cursor1, 2 다음으로 지정을 해줘야 하니 3,4로 지정해 줍니다.

span처리를 하지 않았기 때문에 #header ul li.active로 선언하고

#footer a로 지정해 줍니다.

 

📌span처리 된 부분과 동일한 마우스 오버 효과를 줄거기 때문에 HTML에서 지정한 마우스 오버 효과 색상이나 모양은

굳이 변경하지 않았습니다. 

cursor3.addEventListener("mouseenter" , () => {
    cursor.classList.add("active");
    cursor2.classList.add("active");
});
cursor3.addEventListener("mouseleave", () => {
   cursor.classList.remove("active");
   cursor2.classList.remove("active");
});
cursor4.addEventListener("mouseenter" , () => {
   cursor.classList.add("active");
   cursor2.classList.add("active");
});
cursor4.addEventListener("mouseleave", () => {
   cursor.classList.remove("active");
   cursor2.classList.remove("active");
});

cursor3, 4번을 지정해 준 뒤 그 위치에 마우스가 올라가면 오버효과를 줘야하기 때문에

add를 지정해주면 마우스 효과가 생기게 작업해 주고
remove를 지정해주면 마우스 효과가 사라지도록 작업해 줍니다.

GSAP

오늘은 gsap효과를 사용해 마우스 커서를 더 부드럽게 표현해 주도록 하겠습니다.

푸터 밑에 gsap 페이지에서 따온 주소를 입력시켜줍니다,

script src="https://cdnjs.cloudflare.com/ajax/libs/gsap/3.11.5/gsap.min.js"></script>
//gsap
gsap.to(cursor, {duration:0.3, left:e.pageX-5, top: e.pageY-5});
gsap.to(cursor2, {duration:0.8, left:e.pageX-15, top: e.pageY-15});

GSAP는 GrennSock에서 만든 자바스크립트 애니메이션 라이브러리 입니다.

일반적으로 애니메이션 효과는 CSS로 처리하거나 제이쿼리(JQuery)에서 제공하는 .animate()나 fadeIn(), SlideDown() 등으로 구현하는 것이 일반적이지만 GSAP는 제이쿼리보다 20배 이상 퍼포먼스가 좋고 사용법도 간단합니다.

 

기존의 마우스 오버효과

document.querySelector(".mouse__text span").addEventListener("mouseenter", () => {
    cursor.classList.add("active");
    cursor2.classList.add("active");
});
document.querySelector(".mouse__text span").addEventListener("mouseleave", () => {
      cursor.classList.remove("active");
      cursor2.classList.remove("active");
});

마우스가 span설정 된 글자 위에 올라왔을 때 오버효과를 사용하기 위하여 스크립트를 짜줍니다.

여기서 마우스 효과가 두 개이기 때문에 커서를 두 개 만들고, span처리 된 부분과 처리되지 않은 부분의 효과를 두 개 표현

하기 위해 총 네 번을 작성해 줍니다.

기존을 forEach 로 바꿔 사용하기

document.querySelectorAll(".mouse__text span").forEach(function(span){
   span.addEventListener("mouseenter",function(){
       cursor.classList.add("active");
       cursor2.classList.add("active");
})
   span.addEventListener("mouseleave",function(){
       cursor.classList.remove("active");
       cursor2.classList.remove("active");
    })
});

기존의 스크립트를 짜는 것 또한 반복문이기 때문에

forEach를 사용해 좀 더 쉽고 가독성이 좋게 스크립트를 작성해 주면 완성입니다.

 

📜 몰랐던 속성

속성 설명
GSAP GSAP는 GrennSock에서 만든 자바스크립트 애니메이션 라이브러리입니다.
transition: transform CSS의 transition 속성을 사용하여 요소의 transform 속성이 변경될 때 애니메이션을 적용하는 데 사용됩니다.
transition 요소가 특정 상태에서 다른 상태로 전환 될 때, 즉 마우스 오버, 클릭 또는 키보드 포커스와 같은 이벤트에 응답하여 요소가 전환 될 때 사용됩니다.

 

완성작입니다 🥰

http://127.0.0.1:5500/javascript/mouseEffect/mouseEffect02.html