CSS와 자바 스크립트를 사용한 3D 애니메이션

리자 칸 |

Steam에는 Dota 2라는 게임이 있습니다. 그들은 당신이 플레이하는 캐릭터를 보여주는 "카드"섹션을 가지고 있습니다. 카드 위로 마우스를 가져 가면 정말 멋진 애니메이션이 있습니다. 카드가 위로 올라가 마우스 포인터쪽으로 회전합니다.

사진이 첨부되어 있습니다. 빨간색 점은 마우스가 가리키는 위치를 나타냅니다.

왼쪽 하단 : 여기에 이미지 설명 입력

센터: 여기에 이미지 설명 입력

왼쪽 중앙 : 여기에 이미지 설명 입력

현재 https://codepen.io/riza-khan/pen/mdyvEeg에 기본 버전이 있지만 애니메이션이 의도 한대로 작동하지 않습니다.

Codepen 링크가 Stackoverflow에서 허용되지 않으면이 질문 끝에 코드를 게시 할 것입니다. 일부 코드는 중복되지만 더 많은 통찰력을 얻기 위해 거기에 보관했습니다.

const container = document.querySelector('.container')
const card = document.querySelector('.card')
let x = document.querySelector('.x-axis')
let y = document.querySelector('.y-axis')

container.addEventListener('mousemove', (e) => {
  let xCoords = e.offsetX
  let yCoords = e.offsetY

  x.innerHTML = `xCoords:${xCoords}`
  y.innerHTML = `yCoords:${yCoords}`

  card.style.transform = `rotateY(${yCoords}deg) rotateX(${xCoords}deg) scale(1.1)`
})  

container.addEventListener('mouseout', (e) => {
  card.style.transform = `rotateY(0deg) rotateX(0deg) scale(1)`
})

container.addEventListener('click', (e) => {
  console.log(e)
})
body {
  display: flex;
  height: 90vh;
  background: grey;
}

.x-axis,
.y-axis {
  position: absolute;
}

.y-axis {
  left:100px;
}

.container {
  margin: auto;
}

.card {  
  height: 500px;
  width: 300px;  
  border-radius: 10px;  
  overflow: hidden;
  transition: all 1s ease;  
  box-shadow: 10px 8px 20px -20px black;

  img {
    width: 100%;
    height: 100%;
    object-fit: cover;
  }
}

.container:hover  {

  .card {        
    transform-style: preserve-3d;
  }
}
<p class="x-axis"></p>
<p class="y-axis"></p>

<div class="container">
  <div class="card">
    <img src="https://vignette.wikia.nocookie.net/wowwiki/images/d/d9/Illidan.png/revision/latest?cb=20140503134345" alt="">
  </div>
</div>

Richard

This is what you're looking for. To give a 3D feel to an object, you have to use the CSS property perspective. Here's a working example (also available on CodePen):

const container = document.querySelector('.container')
const card = document.querySelector('.card')
const output = document.querySelector('.output')
let x = document.querySelector('.x-axis')
let y = document.querySelector('.y-axis')

container.addEventListener('mousemove', (e) => {
  let xOffset = e.offsetX
  let yOffset = e.offsetY
  let cardHeight = card.clientHeight
  let cardWidth = card.clientWidth
  let heightCenter = Math.round(cardHeight / 2)
  let widthCenter = Math.round(cardWidth / 2)
  let rotateBaseValue = 20
  let rotateXValue = (yOffset - heightCenter) / heightCenter * rotateBaseValue
  let rotateYValue = (widthCenter - xOffset) / widthCenter * rotateBaseValue

  card.style.transform = `scale(1.1) rotateX(${rotateXValue}deg) rotateY(${rotateYValue}deg)`
})

container.addEventListener('mouseout', (e) => {
  card.style.transform = ''
})
html,
body {
  margin: 0;
  padding: 0;
  height: 100%;
  width: 100vw;
  overflow: hidden;
}

body {
  display: flex;
  background: url(https://pbs.twimg.com/media/DySLFjlV4AEWf_F.jpg) no-repeat;
  background-position: center bottom;
  background-size: cover;
}

.container {
  margin: auto;
  perspective: 1000px;
}

.card {
  height: 25vw;
  width: 15vw;
  border-radius: 10px;
  overflow: hidden;
  transition: all .25s linear;
}

.card img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.container:hover .card {
  box-shadow: 10px 30px 50px -6px black;
}
<div class="container">
  <div class="card">
    <img src="https://66.media.tumblr.com/baf4a8fec55a6cb6fd7b18a7855998e4/tumblr_ply7xcI7pl1sjt61g_540.png" alt="Moonlight Cookie's Alluring Crescent Moon Costume">
  </div>
</div>

EDIT

As per request, I will explain how I got the formula for rotateXValue and rotateYValue.

Before getting into that, you need to know what rotateX and rotateY do. rotateX rotates an item on the horizontal axis (x-axis) and rotateY rotates an item on the vertical axis (y-axis). Positive value on both rotateX and rotateY means that their movements are clockwise; negative means that their movements are counter-clockwise.

Try holding up a piece of paper. You'll notice that if you rotate the paper a little (doesn't matter how many degrees exactly) counter-clockwise on both x-axis and y-axis, you'll see that the paper seems exactly like when you are hovering on the top-right corner of the card. Try clockwise on both x-axis and y-axis, you'll see that the paper's pointing towards you like when you are hovering on the bottom-left corner of the card. Try all four combinations of different rotation directions.

After doing the above experiment, you can soon conclude that:

  • Top-left corner: rotateX counter-clockwise, rotateY clockwise
  • Top-right corner: rotateX and rotateY counter-clockwise
  • Bottom-left corner: rotateX and rotateY clockwise
  • Bottom-right corner: rotateX clockwise and rotateY counter-clockwise

Say that the maximum rotation is 15degrees. On the x-axis, value ranges from 15degrees to -15degrees (from left to right). On the y-axis, value ranges from -15degrees to 15degrees (from top to bottom). The card does not rotate when you're hovering in the middle of the card. Calculate the y-axis. The center is when the value is 0degree. Simply subtract the current y-offset with the center-offset and you'll get how much the distance is from the center-offset. Convert that to fraction relative to center-offset by dividing with the center-offset value. Multiply the fractional value to the maximum degrees to get how many degrees to rotate. Do the same with the x-axis (in this case, you need to invert the subtraction because the value ranges from positive to negative).

P.S.: This one was extremely fun to make. Thanks for the idea!

이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.

침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제

에서 수정
0

몇 마디 만하겠습니다

0리뷰
로그인참여 후 검토

관련 기사

분류에서Dev

자바 스크립트없이 순수한 CSS3로이 애니메이션을 할 수 있습니까?

분류에서Dev

CSS와 자바 스크립트를 사용한 반응 형 메뉴 바

분류에서Dev

Matplotlib를 사용한 수소 원자의 3D 애니메이션

분류에서Dev

자바 스크립트를 사용하여 CSS 애니메이션을 불러오는 방법

분류에서Dev

css3 애니메이션에서 자바 스크립트 제거

분류에서Dev

내 asp.net 애플리케이션에서 CSS와 자바 스크립트 메뉴를 어떻게 사용할 수 있습니까?

분류에서Dev

SetTimeout ()을 사용한 자바 스크립트 캔버스 애니메이션

분류에서Dev

setInterval을 사용한 자바 스크립트 캔버스 애니메이션

분류에서Dev

자바 스크립트 트리거링 CSS 애니메이션

분류에서Dev

matplotlib를 사용한 3D 애니메이션

분류에서Dev

이미지 회전을위한 CSS3 애니메이션, 자바 스크립트로 제어되는 매개 변수

분류에서Dev

애니메이션과 자바 스크립트 및 CSS 혼합

분류에서Dev

자바 스크립트로 CSS 애니메이션 최적화

분류에서Dev

자바 스크립트를 사용한 Nivo 슬라이더 컨트롤 탐색 애니메이션

분류에서Dev

애니메이션 용 자바 스크립트 재생 버튼

분류에서Dev

자바 스크립트 롤 주사위 애니메이션

분류에서Dev

일반적인 무한 루프와 비교되는 HTML5 자바 스크립트 애니메이션?

분류에서Dev

자바 스크립트와 PHP를 사용하여 별도의 페이지에서 다르게 애니메이션 된 헤더

분류에서Dev

CSS 또는 CSS3 애니메이션을 사용한 선형 와이프 텍스트 효과

분류에서Dev

Codeigniter : 자바 스크립트와 PHP를 사용한 테이블 목록

분류에서Dev

애니메이션 메뉴 : 캔버스 또는 자바 스크립트를 사용해야합니까?

분류에서Dev

자바 스크립트 / CSS를 사용한 콘텐츠 슬라이드 쇼

분류에서Dev

자바 스크립트를 사용하여 스프라이트 애니메이션 만들기 (5 초마다)

분류에서Dev

자바 스크립트 바이너리 애니메이션 무한 루프

분류에서Dev

순수 자바 스크립트를 사용하여 토스트 애니메이션

분류에서Dev

자바 스크립트와 CSS 애니메이션이 계속 동기화되지 않습니다.

분류에서Dev

자바 스크립트를 사용하여 단일 라인 차트 애니메이션

분류에서Dev

자바 스크립트 / CSS-CSS 애니메이션 후 회전

분류에서Dev

여러 링크에 대한 자바 스크립트 애니메이션?

Related 관련 기사

  1. 1

    자바 스크립트없이 순수한 CSS3로이 애니메이션을 할 수 있습니까?

  2. 2

    CSS와 자바 스크립트를 사용한 반응 형 메뉴 바

  3. 3

    Matplotlib를 사용한 수소 원자의 3D 애니메이션

  4. 4

    자바 스크립트를 사용하여 CSS 애니메이션을 불러오는 방법

  5. 5

    css3 애니메이션에서 자바 스크립트 제거

  6. 6

    내 asp.net 애플리케이션에서 CSS와 자바 스크립트 메뉴를 어떻게 사용할 수 있습니까?

  7. 7

    SetTimeout ()을 사용한 자바 스크립트 캔버스 애니메이션

  8. 8

    setInterval을 사용한 자바 스크립트 캔버스 애니메이션

  9. 9

    자바 스크립트 트리거링 CSS 애니메이션

  10. 10

    matplotlib를 사용한 3D 애니메이션

  11. 11

    이미지 회전을위한 CSS3 애니메이션, 자바 스크립트로 제어되는 매개 변수

  12. 12

    애니메이션과 자바 스크립트 및 CSS 혼합

  13. 13

    자바 스크립트로 CSS 애니메이션 최적화

  14. 14

    자바 스크립트를 사용한 Nivo 슬라이더 컨트롤 탐색 애니메이션

  15. 15

    애니메이션 용 자바 스크립트 재생 버튼

  16. 16

    자바 스크립트 롤 주사위 애니메이션

  17. 17

    일반적인 무한 루프와 비교되는 HTML5 자바 스크립트 애니메이션?

  18. 18

    자바 스크립트와 PHP를 사용하여 별도의 페이지에서 다르게 애니메이션 된 헤더

  19. 19

    CSS 또는 CSS3 애니메이션을 사용한 선형 와이프 텍스트 효과

  20. 20

    Codeigniter : 자바 스크립트와 PHP를 사용한 테이블 목록

  21. 21

    애니메이션 메뉴 : 캔버스 또는 자바 스크립트를 사용해야합니까?

  22. 22

    자바 스크립트 / CSS를 사용한 콘텐츠 슬라이드 쇼

  23. 23

    자바 스크립트를 사용하여 스프라이트 애니메이션 만들기 (5 초마다)

  24. 24

    자바 스크립트 바이너리 애니메이션 무한 루프

  25. 25

    순수 자바 스크립트를 사용하여 토스트 애니메이션

  26. 26

    자바 스크립트와 CSS 애니메이션이 계속 동기화되지 않습니다.

  27. 27

    자바 스크립트를 사용하여 단일 라인 차트 애니메이션

  28. 28

    자바 스크립트 / CSS-CSS 애니메이션 후 회전

  29. 29

    여러 링크에 대한 자바 스크립트 애니메이션?

뜨겁다태그

보관