提示:如果是webpack环境的,参考:Pag格式在vue3中的简单使用方法_pag文件-CSDN博客
下面展示的是在vite环境下配置pag
1、安装libpag
npm i libpag --save
2、安装rollup-plugin-copy
npm i rollup-plugin-copy --save
3、封装pag组件
下面是一个完整的pag组件,我命名为pagImg
<template><div><canvas ref="pagRef" class="pag-size"></canvas></div>
</template><script setup lang="ts">
import { nextTick, onMounted, ref, watch } from 'vue'
import { PAGInit } from 'libpag';
const props = defineProps({url: {type: String,default: '',}
})
const pagRef = ref() //元素 必须使用ref获取元素,别用id选择器
const urlValue = ref(props.url) //https://www.mustake.net/loading.pagconst initPag = async () => {// console.log("has-pag-->", urlValue.value);if (!pagRef.value) return//判断画布是否存在// 实例化 PAGconst PAG = await PAGInit();// 获取 PAG 素材数据const buffer = await fetch(`${urlValue.value}`).then((response) => response.arrayBuffer());// 加载 PAG 素材为 PAGFile 对象const pagFile = await PAG.PAGFile.load(buffer);// 实例化 PAGView 对象const pagView = await PAG.PAGView.init(pagFile, pagRef.value);if (pagView) {pagView.setRepeatCount(0) // 0表示无限循环,大于0表示循环次数await pagView.play();// 播放 PAGView}
}watch(() => props.url, (val) => {urlValue.value = val
})
onMounted(() => {nextTick(() => {initPag()})
})
</script><style>
.pag-size {/* 根据实际pag动图设置画布尺寸 */width: 60px;height: 60px;position: absolute;left: 50%;bottom: -10px;transform: translateX(-50%);z-index: 3;
}
</style>
4,在vite.config.js中进行配置,目的是把加载pag文件所需的libpag.wasm复制到项目的dist包中
官网的配置链接源码:pag-web/vue/vue3/vite.config.js at main · libpag/pag-web · GitHub
import { defineConfig } from 'vite'
import vue from '@vitejs/plugin-vue'
import copy from 'rollup-plugin-copy'
// https://vitejs.dev/config/
export default defineConfig({plugins: [vue(),copy({targets: [{ src: './node_modules/libpag/lib/libpag.wasm', dest: process.env.NODE_ENV === 'production' ? 'dist/' : 'public/' },],hook: process.env.NODE_ENV === 'production' ? 'writeBundle' : "buildStart",}),],base: './',
});
5.使用pag,下面进提供参考
<template><div v-if="urlValue"><pagImg v-if="fileType === 'pag'" :url="generateImgURL(urlValue)" /></div>
</template>
<script lang='ts' setup>
import pagImg from './pagImg.vue'
import { onMounted, ref, watch } from 'vue'
import { generateImgURL } from '@/utils'; // 我项目封装的路径地址,根据自己需求,获取到完整的pag文件路径
const props = defineProps({url: {type: String,default: '',}
})
const urlValue = ref(props.url) //https://www.mustake.net/loading.pag
const fileType = ref('') // pag svga
const getExt = (fileUrl: string) => {// 判断是否是pag文件if (!fileUrl) { return "" };// 获取文件后缀名return fileUrl.split('.').pop()?.toLowerCase() || '';
}watch(() => props.url, (val) => {// console.log('pag-->', val);urlValue.value = valfileType.value = getExt(val)
})
onMounted(() => {// console.log('监pag-onMounted->', generateImgURL(urlValue.value));fileType.value = getExt(urlValue.value)
})
</script>
<style scoped lang='scss'></style>