DEV Community

iDev-Games
iDev-Games

Posted on

1

How to make a 3D Rotating Cube on Scroll with Trig.js

πŸš€ Create a Stunning 3D Rotating Cube That Spins on Scroll!

Have you ever wanted to create scroll animations that feel magical, without heavy JavaScript libraries slowing down your site? What if I told you that you can make a 3D cube spin on scroll effortlessly, using just CSS and Trig.js?

In this post, I’ll show you how to pin an element using position: sticky; and let Trig.js handle the scroll-based rotation. The result? A mesmerizing effect where the cube spins while staying in place, allowing the background to keep scrolling!

πŸŽ₯ Check out the live CodePen demo


πŸ›  What We’re Building

With just a few lines of CSS and Trig.js, we’ll create:

βœ… A 3D cube that rotates smoothly when you scroll

βœ… A scroll interaction where the cube stays fixed while the page moves

βœ… A lightweight solution that doesn’t require GSAP or ScrollMagic


✨ The Magic of Trig.js

We enable Trig.js on the parent element and use its CSS variables (--trig) on child elements. This lets us animate anything on scroll through CSS.

<div class="pinContainer" data-trig data-trig-degrees="true" data-trig-min="-200" data-trig-max="200">
  <div class="cubeContainer">
      <div class="cube">
          <div class="cube-face front"><span>Front</span></div>
          <div class="cube-face back"><span>Back</span></div>
          <div class="cube-face left"><span>Left</span></div>
          <div class="cube-face right"><span>Right</span></div>
          <div class="cube-face top"><span>Top</span></div>
          <div class="cube-face bottom"><span>Bottom</span></div>
      </div>
  </div>
</div>
Enter fullscreen mode Exit fullscreen mode

πŸ“Œ Pinning the Cube with position: sticky

This keeps the cube in place while the background scrolls:

.cubeContainer {
  position: sticky;
  top: 30%;
}
Enter fullscreen mode Exit fullscreen mode

πŸ”„ Rotating the Cube on Scroll

Using Trig.js, we apply dynamic rotations via CSS variables:

.cube {
  transform: rotateX(calc(var(--trig-deg) - 60deg)) rotateY(var(--trig-deg-reverse));
}
Enter fullscreen mode Exit fullscreen mode

πŸ§ͺ Try It Yourself!

This technique can be used for:

🎨 Interactive storytelling with 3D elements

πŸ–₯ Landing pages that grab attention

What will YOU create with it? πŸ€”


πŸ“’ Join the Trig.js Challenge!

Got a cool animation idea? Share it in the Trig.js Challenge!

For more deep dives into scroll animations, check out:

πŸ‘‰ CSS + JS for Scroll Animations – Here's Why


πŸ”— Resources

πŸ’‘ Drop a comment below if you try this out! Let’s build something awesome together! πŸš€

Top comments (0)