728x90
마우스 이펙트_04 : 마우스를 추적하는 백그라운드 효과 만들어보기!
마우스가 위치한 곳에따라 백그라운드 이미지가 마우스를 따라가는 효과를 만들어보도록 하겠습니다!
HTML 코드
간단하게 HTML을 구성해 뼈대를 구축해봅시다!
<section id="mouseType">
<div class="mouse__cursor"></div>
<div class="mouse__wrap">
<figure>
<img src="../../../assets/slider/effect_bg_04.jpg" alt="">
<figcaption>
<p>winner winner chicken dinner!</p>
<p>잠을 일찍 자는자가 세상을 지배한다.</p>
</figcaption>
</figure>
</div>
</section>
CSS 코드
간단하게 예제를 위해 살을 붙여주기 위해서 하단의 CSS를 작성해 붙여넣어 줍니다.
/* mouseType */
.mouse__wrap {
width: 100%;
height: 100vh;
display: flex;
justify-content: center;
align-items: center;
flex-direction: column;
color: #fff;
overflow: hidden;
/* cursor: none; */
}
.mouse__wrap figure {
width: 50vw;
height: 50vh;
/* background: #ccc; */
position: relative;
overflow: hidden;
transition: transform 500ms ease;
cursor: none;
}
.mouse__wrap figure:hover {
transform: scale(1.025);
}
.mouse__wrap figure img {
position: absolute;
left: -5%;
top: -5%;
width: 110%;
height: 110%;
object-fit: cover;
}
.mouse__wrap figure figcaption {
position: absolute;
left: 50%;
top: 50%;
transform: translate(-50%, -50%);
text-align: center;
font-size: 16px;
line-height: 1.4;
white-space: nowrap;
font-weight: 400;
}
.mouse__cursor {
position: absolute;
left: 0;
top: 0;
width: 20px;
height: 20px;
background: #fff;
border-radius: 50%;
z-index: 1000;
user-select: none;
pointer-events: none;
}
JS 코드 : GSAP를 통해 부드럽게 이동시켜주기
0. 마우스 좌표 값은 pageX/pageY를 통해 각각 변수 mousePageX/mousePageY에 저장시켜 준 뒤
1. 브라우저 창의 너비값과 높이값을 구해 그 값을 절반 나눠 중심의 값을 구한 뒤
그 값을 마우스 값의 좌표를 빼줘 'centerPageX'와 'centerPageY'라는 변수에 각각 저장 시킨 뒤
2. imgMove 라는 변수에는 추적하고자 하는 배경 클래스를 짚고
3. gsap을 통해 imgMove가 centerPageX와 centerPageY 값에 따라 위치를 변화시켜줍니다.
const cursor = document.querySelector(".mouse__cursor");
const cursorRect = cursor.getBoundingClientRect();
document.querySelector(".mouse__wrap figure").addEventListener("mousemove", (e) => {
// 커서
gsap.to(cursor, {
duration: .2,
left: e.pageX - cursorRect.width / 2,
top: e.pageY - cursorRect.height / 2,
})
//마우스 좌표 값
let mousePageX = e.pageX;
let mousePageY = e.pageY;
// 전체 가로
// window.innerWidth; //1680 : 브라우저 크기
// window.outerWidth; //774 : 브라우저 크기 (스크롤바 포함)
// window.screen.width; //1680 : 화면 크기
// 마우스 좌표 값 가운데로 초기화
// 전체 길이/2 - 마우스 좌표값 == 0
let centerPageX = window.innerWidth/2 - mousePageX;
let centerPageY = window.innerHeight/2 - mousePageY;
//이미지 움직이기
const imgMove = document.querySelector(".mouse__wrap figure img");
// imgMove.style.transform = "translate("+centerPageX/20+"px, "+centerPageY/20+"px)";
gsap.to(imgMove, {
duration: 0.3,
x: centerPageX/20,
y: centerPageY/20,
})
})
결과
728x90
반응형
'JS 응용하기' 카테고리의 다른 글
서치 이펙트_04 : map/find를 사용하여 원하는 CSS 속성 찾기! (7) | 2022.09.29 |
---|---|
마우스 이펙트_05 : 원근감을 이용해 좌표값에 따라 3d 효과 주기! (6) | 2022.09.29 |
마우스 이펙트 03 (3) | 2022.09.22 |
패럴렉스 이펙트_05 : 이질감이 느껴지는 패럴렉스 이펙트 만들어보기! (4) | 2022.09.20 |
슬라이드 이펙트_04 : 이전/다음 버튼을 통해 슬라이드를 구현해봅시다 👀 (6) | 2022.09.19 |
댓글