播放动画
阅读时间:2分钟更新于 2025-08-28 14:20
读这篇的前提,建议你已经了解 Galacean Effects 。
开始使用
1. 安装依赖
使用 npm 安装 Galacean Effects 播放器 @galacean/effects
$ npm install @galacean/effects
2. 设置 Dom 容器
<body>
<!-- 这个容器将是显示区域的大小 -->
<div id="container" style="width: 100vw; height: 100vh;"></div>
</body>
3. 创建 Galacean Effects 播放器
import { Player } from '@galacean/effects';
// 动画资源
const myAnimation = '${AnimationPath}';
// 降级图片
const downgradeImage = '${DowngradeImagePath}';
// 实例化一个 Galacean Effects 播放器
const player = new Player({
container: document.getElementById('container'),
/**
* 可捕获异常的时机:
* 1. 初始化 `Player` 遇到异常(包含 `webglcontextlost` 事件)
* 2. `loadScene` 运行时异常(包含资源加载失败以及 `rendererror` 异常等)
* 3. 非以上两种情况,请自行 try/catch 捕获
*/
onError: (err, ...args) => {
// 降级逻辑,以下仅供参考
const containerStyle = container.style;
containerStyle.backgroundImage = `url(${downgradeImage})`;
containerStyle.backgroundRepeat = 'no-repeat';
containerStyle.backgroundSize = 'cover';
containerStyle.backgroundPosition = 'center';
},
});
// 加载动画资源并播放
await player.loadScene(myAnimation);
// 如果播放器循环使用,页面退出时销毁可能剩余的 WebGL 资源
window.addEventListener('unload', () => player.dispose());
注意:
- 如果使用
onError
回调捕获异常,则以上两种时机无需再用try/catch
捕获 - 如果不使用
onError
回调,则以上两种时机务必需要自行用try/catch
捕获异常
你也可以直接使用 @galacean/effects
的 CDN 链接:
<script src="https://unpkg.com/@galacean/effects@1.5.0/dist/index.min.js">
</script>
<script>
// 所有 export 对象挂在 window.ge 上
const player = new window.ge.Player({ container });
</script>
注意:
以上 CDN 链接仅供开发测试,生产环境请使用正式稳定的 CDN 服务。
React 创建播放器
React 写法,使用 ref
函数:
import { Player } from '@galacean/effects';
import React, { memo, useLayoutEffect, useRef } from 'react';
// 动画资源
const myAnimation = '${AnimationPath}';
// 降级图片
const downgradeImage = '${DowngradeImagePath}';
function PlayerComponent(props){
const containerRef = useRef<HTMLDivElement | null>(null);
const playerRef = useRef<Player | null>(null);
useLayoutEffect(function () {
if (!playerRef.current) {
// 实例化一个 Galacean Effects 播放器
const player = playerRef.current = new Player({
container: containerRef.current,
onError: (err, ...args) => {
// 降级逻辑
console.error(err);
},
});
// 加载动画资源并播放
void player.loadScene(myAnimation);
}
return function () {
playerRef.current?.dispose();
playerRef.current = null;
}
}, [props.show]);
// 如果不播放,注意检查container的div尺寸是否正确
return props.show && <div class="container" style={{width:"100vw",height:"100vh"}} ref={containerRef}></div>
}
Preview