[GSAP] 3D Carousel 구현하기

Carrie·2024년 11월 22일
0
post-thumbnail

gsap을 이용하여 원통 모양으로 회전하는 3d carousel을 구현하였다. 마우스 드래그 또는 마우스 휠로 carousel 회전 및 이동이 가능하다.

동작 구현은 아래와 같이 했다.

let xPos = 0;
let zValue = 2000;

gsap.timeline()
    .set(".carousel-item", {
        rotateY: (i) => i * -22.5, // 각 요소를 -22.5도씩 회전시켜 원통형으로 배치
        transformOrigin: `50% 50% ${zValue}px`, // 회전 중심을 설정
        translateZ: -zValue, // 각 요소를 z축 방향으로 이동하여 깊이감을 줌
  		backfaceVisibility: "hidden", // 요소의 뒷면이 보이지 않도록 설정
    }); 

    $(document).on("mousedown touchstart", dragStart);
    $(document).on("mouseup touchend", dragEnd);
    $(window).on("wheel", handelWeel);

	// 드래그 시작
    function dragStart(e) {
        e.preventDefault();
        e.stopPropagation();

        if (e.touches) e.clientX = e.touches[0].clientX; // 드래그 시작한 위치
        xPos = Math.round(e.clientX);

        $(document).on("mousemove touchmove", drag);
    }

	// 드래그 중
    function drag(e) {
        e.preventDefault();
        e.stopPropagation();

        gsap.to(".carousel-list", {
          	// 드래그 시작한 위치 - 현재 마우스 위치
          	// -> 드래그한 거리만큼 회전시킴
            rotateY: "+=" + (xPos - Math.round(e.clientX)), 
        });
        xPos = Math.round(e.clientX); // 현재 마우스 위치 업데이트
    }

	// 드래그 종료
    function dragEnd(e) {
        e.preventDefault();
        e.stopPropagation();
        
      	// 이벤트 리스너를 제거하여 드래그 종료
        $(document).off("mousemove touchmove", drag); 
    }

	// 마우스 휠 이벤트
    function handelWeel(e) {
      	// 스크롤 방향 가져오기 (스크롤을 올릴 때 양수, 스크롤을 내릴 때 음수)
        const deltaY = e.originalEvent.deltaY; 
        gsap.to(".carousel-list", {
          	// 스크롤 방향에 따라 22.5도씩 회전
            rotateY: "+=" + (deltaY > 0 ? 22.5 : -22.5),
        });
    }

👉 전체 코드


📌 참고
https://gsap.com/community/forums/topic/31694-3d-rounded-carousel-with-gsap/

profile
Markup Developer🧑‍💻

0개의 댓글