PAG官网:官网
https://pag.art/docs/sdk.html#web-端接入
一、创建依赖准备
libpag.min.js
libpag.wasm
去git上下载就行了
https://github.com/Tencent/libpag/releases/tag/v4.3.3
下载 libpag_4.3.3_web.zip 里边有
两个文件放到 public 中
二、index.html引入
只引入这一个就行
<script src="libpag.min.js"></script>
三、创建组件
<script>
export default {
name: "CanvasPag",
props: {
canvasId: String,
url: String,
scaleWidth: {
type: Number,
default: 0.58
},
scaleHeight: {
type: Number,
default: 0.58
},
canvasStyle: String,
},
data() {
return {
renderingId: undefined,
canvasRef: undefined,
}
},
created() {
this.renderingId = this.canvasId || this.randomId()
},
mounted() {
this.createdPag()
},
methods: {
randomId(lenNum, radixNum) {
let len = lenNum || 32, radix = radixNum || 16
let chars = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'.split('')
let uuid = []
let i
radix = radix || chars.length
if (len) {
for (i = 0; i < len; i++) uuid[i] = chars[0 | Math.random() * radix]
} else {
var r
uuid[8] = uuid[13] = uuid[18] = uuid[23] = '-'
uuid[14] = '4'
for (i = 0; i < 36; i++) {
if (!uuid[i]) {
r = 0 | Math.random() * 16
uuid[i] = chars[(i === 19) ? (r & 0x3) | 0x8 : r]
}
}
}
return uuid.join('')
},
async createdPag() {
const PAG = await window.libpag.PAGInit();
let url = "/pag/" + this.url + ".pag"
let id = this.renderingId
const buffer = await fetch(url).then((response) => {
return response.arrayBuffer()
})
const pagFile = await PAG.PAGFile.load(buffer)
// 设置宽高
const pagComposition = PAG.PAGComposition.make(pagFile.width(), pagFile.height());
// 宽高的缩放比例
const matrix1 = PAG.Matrix.makeScale(this.scaleWidth, this.scaleHeight);
// 修改比例
pagFile.setMatrix(matrix1);
pagComposition.addLayer(pagFile);
const canvas = document.getElementById(id);
if (canvas !== null) {
canvas.width = pagComposition.width();
canvas.height = pagComposition.height();
const pagView = await PAG.PAGView.init(pagComposition, canvas);
// Set PAGView play infinity.
pagView.setRepeatCount(0);
await pagView.play();
this.canvasRef = pagView
}
},
async destroy() {
const pagDom = document.querySelectorAll('.pag-zk');
if (pagDom) {
console.log('webgl清空内容')
await pagDom.forEach((item)=>{
const gl = item.getContext("webgl");
gl.clear(gl.COLOR_BUFFER_BIT);
})
}
if (this.canvasRef?.pagSurface) {
console.log('pag清空内容')
await this.canvasRef.pagSurface.clearAll();
}
if (this.canvasRef?.isPlaying) {
this.canvasRef.isPlaying = false
}
await this.canvasRef?.destroy();
}
},
beforeDestroy() {
this.destroy()
}
}
</script>
<template>
<canvas :id="renderingId" :style="canvasStyle" :key="renderingId + 'pagkey'" class="pag-zk"></canvas>
</template>
四、main.js注册全局组件
import CanvasPag from '@/components/CanvasPag/index.vue'
Vue.component('canvas-pag',CanvasPag)
五、页面使用
<canvas-pag
key="jkzt-blue"
url="yxzz"
style="position: absolute;top: -22px;"
></canvas-pag>