JAVASCRIPT/자바스크립트

mouseEffect04 - 이미지 효과1

(*ᴗ͈ˬᴗ͈)ꕤ*.゚ 2022. 3. 8. 16:55

HTML 구성

<div class="mouse__wrap">
    <div class="mouse__img">
        <figure>
            <img src="img/images1.jpg" alt="이미지">
        </figure>
        <figcaption>
            <p>Life is not fair. Get used to it.</p>
            <p>삶은 공평하지 않다. 그런 삶에 익숙해져라.</p>
        </figcaption>
    </div>
</div>

어떤 태그로 구성하였는지 간단하게 살펴볼 수 있다

 

.mouse__wrap > .mouse__img > figure > img

.mouse__wrap > .mouse__img > figcaption > p

CSS 구성

.mouse__img {
    position: relative;
}

.mouse__img figure {
    width: 50vw;
    height: 53vh;
    transition: transform 500ms cubic-bezier(0.25, 0.46, 0.45, 0.84);
    position: relative;
    border: 3px solid #fff;
    overflow: hidden;
}

.mouse__img figure:hover {
    transform: scale(1.025);
}

.mouse__img figure img {
    position: absolute;
    left: -5%;top: -5%;
    width: 110%;
    height: 110%;
    object-fit: cover;
}

.mouse__img figcaption {
    position: absolute;
    left: 50%; top: 50%;
    transform: translate(-50%, -50%);
    text-align: center;
    font-size: 1.3vw;
    line-height: 1.6;
    white-space: nowrap;
}

.mouse__img figcaption p {
    background-color: #00000033;
}

살펴볼 CSS

 

1. .mouse__img > figure

- overflow: hidden; 으로 넘치는 부분을 잘라준다

- hover시, 1.025배 확대해준다

 

2. .mouse__img > figure > img 

-width, height 값을 110%로 해준다(움직이는 효과를 줘야하기 때문!)

-object-fit: cover; 

object-fit이란 콘텐츠 크기를 어떤 방식으로 조절해 요소에 맞출 것인지 지정하는 것이다

cover 속성은 가로세로비를 유지하면서, 요소 콘텐츠 박스를 가득 채우는 것!

 

JS 구성

document.querySelector(".mouse__img").addEventListener("mousemove", (e) => {

    //커서를 gsap로 나타내기
    gsap.to(".cursor", {duration: .2, left: e.pageX - circle.width/2, top: e.pageY - circle.height/2});

    //마우스 좌표 값 설정
    let mousePageX = e.pageX;
    let mousePageY = e.pageY;
    
    //노트북 기준 좌표값 확인하기
    let windowWidth1 = window.innerWidth; //1094 
    let windowHeight1 = window.innerHeight; //789
    let windowWidth2 = window.outerWidth; //1440
    let windowHeight2 = window.outerHeight; //900
    let windowWidth3 = window.screen.width; //1440
    let windowHeight3 = window.screen.height; //900
    
    //우리가 필요한 값
    let windowWidth = window.outerWidth;
    let windowHeight = window.outerHeight;

    // 마우스 좌표 값 기준점을 가운데 초기화
    // 전체길이 /2 - 마우스 x 좌표값 = 0
    let centerPageX = window.innerWidth/2 - mousePageX;
    let centerPageY = window.innerHeight/2 - mousePageY;

    //이미지 움직이기(20을 나눠주는 이유는 작은 움직임만 보여주기 위함이다)
    gsap.to(".mouse__img figure img", {duration: 0.3, x: centerPageX/20, y: centerPageY/20});
})

기준점을 가운데로, (0, 0)으로 설정해주고

centerPage를 '화면 중간에서 마우스 위치를 뺴준 값'으로 선언해준다

 

gsap.to(".mouse__img figure img", {duration: 0.3, x: centerPageX/20, y: centerPageY/20});

x축으로 마우스를 20px움직이면 이미지는 1px움직이고,

y축으로 마우스를 20px움직이면 이미지는 1px이 움직이도록 하였고

자연스럽게 연출하기 위해 duration을 0.3으로 주었다

 

 

 

 

링크

https://sungilryuu.github.io/webs_class/javascript/effect/mouseEffect04.html