three.js 之 入门篇 2 之gsap动画的使用
- 安装:
npm install gsap
- 导入:
// 导入动画库 import gsap from "gsap"
- 官网:官网
- 文档:
https://greensock.com/docs/
- 入门指南:getting started guide
1:gsap动画基本使用与原理
import * as THREE from "three"
import { OrbitControls } from "three/examples/jsm/controls/OrbitControls"
import gsap from "gsap"
const scene = new THREE.Scene()
const camera = new THREE.PerspectiveCamera(75,window.innerWidth/ window.innerHeight,0.1,1000)
camera.position.set(0,0,10)
scene.add( camera );
const geometry = new THREE.BoxGeometry( 1, 1, 1 );
const material = new THREE.MeshBasicMaterial( {color: 0x00ff00} );
const mesh = new THREE.Mesh( geometry, material );
scene.add( mesh );
mesh.rotation.set( Math.PI / 4 , 0,0,'XYZ')
const renderer = new THREE.WebGL1Renderer()
renderer.setSize(window.innerWidth,window.innerHeight)
document.body.appendChild(renderer.domElement)
const controls = new OrbitControls(camera,renderer.domElement)
const axesHelper = new THREE.AxesHelper( 5 );
scene.add( axesHelper );
gsap.to(mesh.position,{x:5,duration:5})
gsap.to(mesh.rotation,{x:2*Math.PI,duration:5,ease: "power3.out",})
function animate() {
requestAnimationFrame( animate );
controls.update();
renderer.render( scene, camera );
}
animate()
2:gsap动画基本使用与原理
- mesh.rotation 几何体的旋转 mesh.XXX 几何体的动画
- x轴执行
- duration 动画的执行时间
- ease 动画的执行速度
- repeat 动画执行次数 -1为无线次
- yoyo: 往返运动
- delay 延迟时间 2s后执行 旋转动画
- onStart 动画开始 调用函数
- onComplete 动画完成后 调用函数
import * as THREE from "three"
import { OrbitControls } from "three/examples/jsm/controls/OrbitControls"
import gsap from "gsap"
const scene = new THREE.Scene()
const camera = new THREE.PerspectiveCamera(75,window.innerWidth/ window.innerHeight,0.1,1000)
camera.position.set(0,0,10)
scene.add( camera );
const geometry = new THREE.BoxGeometry( 1, 1, 1 );
const material = new THREE.MeshBasicMaterial( {color: 0x00ff00} );
const mesh = new THREE.Mesh( geometry, material );
scene.add( mesh );
mesh.rotation.set( Math.PI / 4 , 0,0,'XYZ')
const renderer = new THREE.WebGL1Renderer()
renderer.setSize(window.innerWidth,window.innerHeight)
document.body.appendChild(renderer.domElement)
const controls = new OrbitControls(camera,renderer.domElement)
const axesHelper = new THREE.AxesHelper( 5 );
scene.add( axesHelper );
gsap.to(mesh.position,{x:5,duration:5})
var animate1 = gsap.to( mesh.rotation, { x:2*Math.PI, duration:5, ease: "power3.out",
repeat:2,
yoyo:true,
delay:2,
onComplete:()=>{
console.log('动画完成');
},
onStart:()=>{
console.log('动画开始')
}
})
window.addEventListener('dblclick',()=>{
if ( animate1.isActive() ) {
animate1.pause()
} else {
animate1.resume()
}
})
function animate() {
requestAnimationFrame( animate );
controls.update();
renderer.render( scene, camera );
}
animate()