반응형
250x250
Notice
Recent Posts
Recent Comments
Link
관리 메뉴

ZeroToHunnit Coding

[Javascript] 커서따라 3d느낌으로 움직이는 카드 본문

JAVASCRIPT

[Javascript] 커서따라 3d느낌으로 움직이는 카드

0에서100 2023. 12. 31. 16:05
728x90
반응형

위의 사진처럼 카드에 마우스 커서가 올라가면 커서따라 3d느낌으로 위로 솟는 느낌으로 만들어봤다.

 

HTML

  <div class="box">
    <div class="photo"></div>
  </div>

 

CSS

.box{
  width: 511px;
  height: 321px;
  margin-top: 300px;
  margin-left: 500px;
  transition: all 0.1s;
  position: relative;
}

.photo{
  width: 100%;
  height: 100%;
  background-image: url(card.png);
}

 

박스에 크기를 정하고 photo는 background로 이미지를 넣어주었다.

 

JAVASCRIPT

document.querySelector('.box').addEventListener('mousemove', function(e){

let rotateY = -50/511 * e.offsetX + 25
let rotateX = 1/6 * e.offsetY - 25
console.log(rotateX,rotateY)
  document.querySelector('.box').style = `transform : perspective(600px) rotateX(${rotateX}deg) rotateY(${rotateY}deg)`
});

document.querySelector('.box').addEventListener('mouseout', function(e){
    document.querySelector('.box').style = `transform : none`
  })

 

우선 이벤트리스너로 mousemove라는 함수를 사용했고 파라미터 e를 뚫어서 e.offsetX, e.offsetY 즉 박스에서의 마우스 커서의 x축과 y축의 값으로 rotate값을 유동적으로 하는 일차함수를 만들었다. 그리고 마우스가 올라가서 움직이면 perspective라는 3d느낌이 나는 css코드를 600px을 주고 rotateX와 rotateY에 일차함수를 넣었다.

그리고 마우스가 나가면 transform을 none으로 했다.

 

 

728x90
반응형