ThreeJS GSAP动画库综合应用

189 阅读5分钟

本文档涵盖了Three.js与GSAP动画库综合应用的关键技术和实现方法,基于实际代码示例进行讲解,展示如何利用GSAP库创建丰富的3D动画效果。

[动画效果](8576ca30507e4aa1b34c24891cfc6098~tplv-73owjymdk6-jj-mark-v1:0:0:0:0:5o6Y6YeR5oqA5pyv56S-5Yy6IEAg5YmN56uv546L5qCh6ZW_:q75.awebp (772×412) (byteimg.com))

1. GSAP动画库导入与初始化

在项目中使用GSAP动画库需要先导入并进行初始化:

import * as THREE from "three";
// 导入轨道控制器
import { OrbitControls } from "three/examples/jsm/controls/OrbitControls";
// 导入动画库
import gsap from "gsap";
// 导入dat.gui
import * as dat from "dat.gui";

const textureLoader = new THREE.TextureLoader();
const particlesTexture = textureLoader.load("./textures/particles/1.png");

// 1、创建场景
const scene = new THREE.Scene();

// 2、创建相机
const camera = new THREE.PerspectiveCamera(
  75,
  window.innerWidth / window.innerHeight,
  0.1,
  300
);

// 设置相机位置
camera.position.set(0, 0, 18);
scene.add(camera);

// 初始化渲染器
const renderer = new THREE.WebGLRenderer({ alpha: true });
// 设置渲染的尺寸大小
renderer.setSize(window.innerWidth, window.innerHeight);
// 开启场景中的阴影贴图
renderer.shadowMap.enabled = true;
renderer.physicallyCorrectLights = true;

// 将webgl渲染的canvas内容添加到body
document.body.appendChild(renderer.domElement);

// 添加坐标轴辅助器
const axesHelper = new THREE.AxesHelper(5);
scene.add(axesHelper);

// 设置时钟
const clock = new THREE.Clock();

// 鼠标的位置对象
const mouse = new THREE.Vector2();

// 创建投射光线对象
const raycaster = new THREE.Raycaster();

// 红色材质(用于交互效果)
const redMaterial = new THREE.MeshBasicMaterial({
  color: "#ff0000",
});

2. 立方体网格动画

2.1 立方体网格创建

创建一个由多个立方体组成的3D网格,用于第一屏的视觉效果: Title

// 创建立方体几何体
const cubeGeometry = new THREE.BoxBufferGeometry(2, 2, 2);
const material = new THREE.MeshBasicMaterial({
  wireframe: true,                    // 线框模式
});

// 创建立方体网格
let cubeArr = [];
let cubeGroup = new THREE.Group();
for (let i = 0; i < 5; i++) {
  for (let j = 0; j < 5; j++) {
    for (let z = 0; z < 5; z++) {
      const cube = new THREE.Mesh(cubeGeometry, material);
      cube.position.set(i * 2 - 4, j * 2 - 4, z * 2 - 4);  // 设置立方体位置
      cubeGroup.add(cube);
      cubeArr.push(cube);
    }
  }
}

scene.add(cubeGroup);

2.2 立方体网格旋转动画

使用GSAP库实现立方体网格的连续旋转动画:

// 立方体网格旋转动画
gsap.to(cubeGroup.rotation, {
  x: "+=" + Math.PI * 2,              // X轴旋转一周
  y: "+=" + Math.PI * 2,              // Y轴旋转一周
  duration: 10,                        // 动画持续时间10秒
  ease: "power2.inOut",                // 缓动函数
  repeat: -1,                          // 无限重复
});

3. 三角形几何体动画

3.1 随机三角形生成

创建一系列随机形状的三角形,形成独特的视觉效果:

// 创建三角形组
var sjxGroup = new THREE.Group();
for (let i = 0; i < 50; i++) {
  // 每一个三角形,需要3个顶点,每个顶点需要3个值
  const geometry = new THREE.BufferGeometry();
  const positionArray = new Float32Array(9);
  for (let j = 0; j < 9; j++) {
    if (j % 3 == 1) {
      positionArray[j] = Math.random() * 10 - 5;  // Y轴特殊处理
    } else {
      positionArray[j] = Math.random() * 10 - 5;
    }
  }
  geometry.setAttribute(
    "position",
    new THREE.BufferAttribute(positionArray, 3)
  );
  
  // 随机颜色
  let color = new THREE.Color(Math.random(), Math.random(), Math.random());
  const material = new THREE.MeshBasicMaterial({
    color: color,
    transparent: true,
    opacity: 0.5,
    side: THREE.DoubleSide,
  });
  
  // 根据几何体和材质创建物体
  let sjxMesh = new THREE.Mesh(geometry, material);
  sjxGroup.add(sjxMesh);
}
sjxGroup.position.set(0, -30, 0);     // 设置三角形组的位置
scene.add(sjxGroup);

3.2 三角形组旋转动画

使用GSAP库实现三角形组的连续旋转动画:

// 三角形组旋转动画
gsap.to(sjxGroup.rotation, {
  x: "-=" + Math.PI * 2,              // X轴反向旋转一周
  z: "+=" + Math.PI * 2,              // Z轴正向旋转一周
  duration: 12,                        // 动画持续时间12秒
  ease: "power2.inOut",                // 缓动函数
  repeat: -1,                          // 无限重复
});

4. 点光源与小球动画

4.1 球体和光源设置

创建一个带有光源的动态场景:

// 创建球体组
const sphereGroup = new THREE.Group();
const sphereGeometry = new THREE.SphereBufferGeometry(1, 20, 20);
const spherematerial = new THREE.MeshStandardMaterial({
  side: THREE.DoubleSide,
});
const sphere = new THREE.Mesh(sphereGeometry, spherematerial);
sphere.castShadow = true;              // 启用阴影投射

sphereGroup.add(sphere);

// 创建平面
const planeGeometry = new THREE.PlaneBufferGeometry(20, 20);
const plane = new THREE.Mesh(planeGeometry, spherematerial);
plane.position.set(0, -1, 0);
plane.rotation.x = -Math.PI / 2;
plane.receiveShadow = true;            // 启用阴影接收
sphereGroup.add(plane);

// 添加环境光
const light = new THREE.AmbientLight(0xffffff, 0.5);
sphereGroup.add(light);

// 创建小球(带光源)
const smallBall = new THREE.Mesh(
  new THREE.SphereBufferGeometry(0.1, 20, 20),
  new THREE.MeshBasicMaterial({ color: 0xff0000 })
);
smallBall.position.set(2, 2, 2);

// 点光源
const pointLight = new THREE.PointLight(0xff0000, 3);
pointLight.castShadow = true;
pointLight.shadow.radius = 20;         // 阴影模糊度
pointLight.shadow.mapSize.set(512, 512); // 阴影贴图分辨率

smallBall.add(pointLight);
sphereGroup.add(smallBall);

sphereGroup.position.set(0, -60, 0);
scene.add(sphereGroup);

4.2 小球位置动画

使用GSAP库实现小球的位置动画,创造弹跳和移动效果:

// 小球水平移动动画
gsap.to(smallBall.position, {
  x: -3,                               // 移动到x=-3位置
  duration: 6,                         // 动画持续时间6秒
  ease: "power2.inOut",                // 缓动函数
  repeat: -1,                          // 无限重复
  yoyo: true,                          // 往返运动
});

// 小球垂直移动动画(弹跳效果)
gsap.to(smallBall.position, {
  y: 0,                                // 移动到y=0位置
  duration: 0.5,                       // 动画持续时间0.5秒
  ease: "power2.inOut",                // 缓动函数
  repeat: -1,                          // 无限重复
  yoyo: true,                          // 往返运动
});

5. 动画循环与渲染

5.1 动画循环函数

实现基本的动画循环和渲染:

function render() {
  let deltaTime = clock.getDelta();

  // 鼠标移动影响相机位置
  camera.position.x += (mouse.x * 10 - camera.position.x) * deltaTime * 5;
  
  renderer.render(scene, camera);
  requestAnimationFrame(render);
}

render(); // 启动动画循环

// 监听鼠标位置
window.addEventListener("mousemove", (event) => {
  mouse.x = event.clientX / window.innerWidth - 0.5;
  mouse.y = event.clientY / window.innerHeight - 0.5;
});

5.2 相机跟随动画

实现相机跟随鼠标移动的动画效果:

// 监听鼠标位置
window.addEventListener("mousemove", (event) => {
  mouse.x = event.clientX / window.innerWidth - 0.5;
  mouse.y = event.clientY / window.innerHeight - 0.5;
});

function render() {
  let deltaTime = clock.getDelta();

  // 鼠标移动影响相机位置
  camera.position.x += (mouse.x * 10 - camera.position.x) * deltaTime * 5;
  
  renderer.render(scene, camera);
  requestAnimationFrame(render);
}

6. 交互动画

6.1 鼠标点击交互动画

实现鼠标点击时的交互效果:

// 创建投射光线对象
const raycaster = new THREE.Raycaster();
const mouse = new THREE.Vector2();

// 监听鼠标点击事件
window.addEventListener("click", (event) => {
  mouse.x = (event.clientX / window.innerWidth) * 2 - 1;
  mouse.y = -((event.clientY / window.innerHeight) * 2 - 1);
  raycaster.setFromCamera(mouse, camera);
  let result = raycaster.intersectObjects(cubeArr);
  
  // 改变相交物体的材质颜色
  result.forEach((item) => {
    item.object.material = redMaterial;
  });
});

总结

本章详细介绍了Three.js中创建3D动画特效的几种主要动画效果:

  1. GSAP动画库导入与初始化:导入GSAP动画库并初始化所需变量
  2. 立方体网格动画:通过GSAP库实现的连续旋转动画,创造动态的3D网格效果
  3. 三角形几何体动画:随机生成的三角形组合,配合旋转动画创造抽象艺术效果
  4. 点光源与小球动画:带动画的小球与点光源,展现动态光影效果
  5. 动画循环与渲染:实现基本的动画循环和渲染机制
  6. 相机跟随动画:实现相机跟随鼠标移动的动画效果

此外,还实现了实现鼠标点击交互效果,共同构成了完整的3D动画体验。通过合理运用Three.js和GSAP动画库,可以创造出丰富多样的3D动画效果。