three-第三方动画库-让物体动起来更简单(gsap)

gsap

介绍:

GreenSock Animation Platform (GSAP) 是一个业界知名的动画库,它被1100多万个网站使用,有超过50%的获奖的网站都是用了它。不管是在原生环境中,还是任意的框架中,你可以使用GSAP去让非常多的东西动起来。不管你是想要去让UI界面产生交互动画,还是SVG图形产生动画,甚至是Threejs还是React组件,GSAP都可以轻松搞定!

相关地址:

https://gsap.framer.wiki/stated   -   中文翻译说明

https://gsap.com/docs/v3/  -   官方文档说明

安装

npm:

npm install gsap

 cdn:

<script src="https://cdnjs.cloudflare.com/ajax/libs/gsap/3.12.5/gsap.min.js"></script>

yarn:

yarn add gsap

参考地址:https://gsap.com/docs/v3/Installation?tab=yarn&module=esm&method=private+registry&tier=free&club=false&require=false&trial=true

gsap和three.js结合

import * as THREE from "three";
import {OrbitControls} from 'three/examples/jsm/controls/OrbitControls';
import gsap from "gsap";
import {func} from "three/examples/jsm/nodes/code/FunctionNode";
// 函数中添加时间
const scene = new THREE.Scene();
const camera = new THREE.PerspectiveCamera(75, window.innerWidth / window.innerHeight, 0.1, 1000);

const renderer = new THREE.WebGLRenderer();
renderer.setSize(window.innerWidth, window.innerHeight);
document.body.appendChild(renderer.domElement);

const geometry = new THREE.BoxGeometry(2, 2, 2);
const material = new THREE.MeshBasicMaterial( { color: 0x00ff00 } );
const cube = new THREE.Mesh( geometry, material );
cube.position.set(1,0,0);
cube.scale.set(0.5,0.5,0.5);
cube.rotation.set(Math.PI / 4, 0, 0, 'XYZ')
scene.add(cube);

camera.position.z = 5;
const controls = new OrbitControls( camera, renderer.domElement );
// 添加阻尼
controls.enableDamping = true;
const axesHelper = new THREE.AxesHelper( 5 );
const animal1 = gsap.to(cube.position, { x: 4, duration: 5, ease: "power2.inOut", repeat: -1, yoyo: true, })
const animal2 = gsap.to(cube.rotation, { x: 2 * Math.PI, duration: 5, ease: "power2.inOut", repeat: -1, yoyo: true, })
document.body.addEventListener('click', function () {
    if (animal1.isActive()) {
        animal1.pause();
    } else {
        animal1.resume()
    }
})
scene.add( axesHelper );
function render() {
    renderer.render(scene, camera);
    requestAnimationFrame(render);
}
render();
window.addEventListener('resize', function () {
    // 更新摄像头
    camera.aspect = window.innerWidth / window.innerHeight;
    // 更新摄像头的投影矩阵
    camera.updateProjectionMatrix();
    // 更新渲染器
    renderer.setSize(window.innerWidth, window.innerHeight);
    renderer.setPixelRatio(window.devicePixelRatio);
});
// 全屏
window.addEventListener("dblclick", function () {
    const fullScreen = document.fullscreenElement;
    if (!fullScreen) {
        renderer.domElement.requestFullscreen();
    } else {
        document.exitFullscreen();
    }
})

展示效果:

 

posted @ 2024-02-23 16:47  上官靖宇  阅读(446)  评论(0编辑  收藏  举报