GSAP in ThreeJS

GreenSock Animation Platform (GSAP) is a powerful JavaScript library used for creating high-performance animations. When combined with Three.js, GSAP offers a simple and effective way to animate 3D objects, adding dynamic interactions and visual effects to your 3D scenes.

Why Use GSAP with Three.js?

GSAP excels at tweening, which involves smoothly transitioning object properties over time. In a Three.js scene, you can use GSAP to animate various properties of 3D objects, such as position, rotation, scale, and even material properties like opacity or color. GSAP’s ease of use and flexibility make it a great tool for enhancing your Three.js projects.

Basic Setup

To start using GSAP with Three.js, include both libraries in your project. If you’re using a module-based setup:

import * as THREE from 'three';
import { gsap } from 'gsap';

Next, set up a basic Three.js scene with a camera, renderer, and a 3D object, like a cube:

// Create a basic scene
const scene = new THREE.Scene();
const camera = new THREE.PerspectiveCamera(75, window.innerWidth / window.innerHeight, 0.1, 1000);
camera.position.z = 5;
const renderer = new THREE.WebGLRenderer();
renderer.setSize(window.innerWidth, window.innerHeight);
document.body.appendChild(renderer.domElement);
// Add a cube
const geometry = new THREE.BoxGeometry();
const material = new THREE.MeshBasicMaterial({ color: 0x00ff00 });
const cube = new THREE.Mesh(geometry, material);
scene.add(cube);

Animating with GSAP

With GSAP, you can animate the cube’s properties effortlessly. For example, to rotate the cube 360 degrees along the y-axis:

gsap.to(cube.rotation, { 
	duration: 2, 
	y: Math.PI * 2, 
	repeat: -1, 
	ease: "power1.inOut"
 });

In this:

  • duration: Sets the time (in seconds) for the animation to complete.
  • y: Math.PI * 2: Specifies the target rotation angle (360 degrees).
  • repeat: -1: Makes the animation loop infinitely.
  • ease: Applies an easing function for smooth acceleration and deceleration.

You can also animate multiple properties simultaneously. To move and scale the cube while rotating it:

gsap.to(cube.position, { duration: 3, x: 2, y: 1, ease: "bounce.out" });
gsap.to(cube.scale, { duration: 2, x: 1.5, y: 1.5, z: 1.5, ease: "elastic.out(1, 0.3)" });

Final Rendering

To ensure the scene updates with the animations, you need a render loop:

function animate() {
  requestAnimationFrame(animate);
  renderer.render(scene, camera);
}
animate();

This loop continuously renders the scene, reflecting any changes made by GSAP animations.

Leave a comment

Your email address will not be published. Required fields are marked *