一、问题
由于项目需求需要使用动图,但是gif体积又十分巨大,只能寻求别的方法,谁让我是牛马呢
PAG官网:https://pag.io/
PAG文档地址:https://pag.io/docs/home.html
PAG Demo下载:https://pag.io/docs/pad-demo-download.html
PAG前端SDK安装:https://pag.io/docs/use-web-sdk.html
PAG测试素材下载:https://pag.io/docs/pag-test-material.html
访问有些慢,等会就OK了
二、解决
1、入口文件
需要再入口文件
index.html
,位置一般在public/index.html
,加入一下代码
<script src="https://cdn.jsdelivr.net/npm/libpag@latest/lib/libpag.min.js"></script>
有时候使用网址,=测试的时候或者部署访问的时候会出现无法访问的错误
这时候可以下载需要的js进行配置
在下载的demo
里面,在lib
文件下,将这三个文件复制到自己项目的public/static
下即可
<script src="/static/js/libpag.min.js"></script>
2、素材文件
这里需要使用上面的素材下载网址了:https://pag.io/docs/pag-test-material.html,访问点击下载就可以
这里将下载的素材文件防到
public/static
文件下
3、代码
下面的代码也可以自己弄成一个组件进行访问,现在就临时展示
<template>
<div class="overlay-center">
<canvas
ref="pagCanvas"
/>
</div>
</template>
<script>
export default {
data() {
return {
pagUrl: '/static/like.pag',
pagView: null,
pagFile: null,
}
},
mounted() {
this.initPagPlayer();
},
beforeDestroy() {
this.destroyPagPlayer();
},
methods: {
async initPagPlayer() {
try {
// 初始化 PAG 库
const PAG = await window.libpag.PAGInit();
// 获取 canvas 元素
const canvas = this.$refs.pagCanvas;
// 加载 PAG 文件
const response = await fetch(this.pagUrl);
const buffer = await response.arrayBuffer();
this.pagFile = await PAG.PAGFile.load(buffer);
// 设置 canvas 尺寸
canvas.width = this.pagFile.width();
canvas.height = this.pagFile.height();
// 创建 PAGView 实例
this.pagView = await PAG.PAGView.init(this.pagFile, canvas);
// 设置无限循环
this.pagView.setRepeatCount(0);
// 开始播放
await this.pagView.play();
} catch (error) {
console.error('加载PAG失败:', error);
}
},
destroyPagPlayer() {
// 释放资源
if (this.pagView) {
this.pagView.destroy();
this.pagView = null;
}
if (this.pagFile) {
this.pagFile.destroy();
this.pagFile = null;
}
}
}
}
</script>
4、访问
访问查看