记录一次使用pdf.js插件触发的canvas渲染类bug
业务场景:点击多个tab标签预览对应的pdf
修改前代码:
//html
<div class="canvas-scale" ref="canvasScale">
<canvas
class="contract-canvas"
:ref="`contractCanvas${index + 1}`"
v-for="(_, index) in pageArray"
:key="index"
></canvas>
</div>
//js
initPdf(url) {
this.pdfLoading = true;
// eslint-disable-next-line no-undef
const loadingTask = pdfjsLib.getDocument(url);
loadingTask.promise.then(
async (pdf) => {
this.allPageNum = pdf.numPages;
this.pageNum = 1;
this.pageArray = Array(pdf.numPages).fill({});
this.pdfObj = pdf;
await this.forRenderPage();
this.pdfLoading = false;
},
(reason) => {
this.pdfLoading = false;
console.error(reason);
},
);
};
async forRenderPage() {
for (let index = 1; index < this.allPageNum + 1; index++) {
await this.renderPage(index);
}
},
async renderPage(pageNumber) {
const page = await this.pdfObj.getPage(pageNumber);
const scale = 2;
const viewport = page.getViewport({ scale });
// 准备画布使用PDF页面尺寸
const canvas = this.$refs[`contractCanvas${pageNumber}`][0];
const context = canvas.getContext('2d');
canvas.height = viewport.height;
canvas.width = viewport.width;
// 渲染PDF页到画布上下文
const renderContext = {
canvasContext: context,
viewport,
};
const renderTask = page.render(renderContext);
renderTask.promise.then(() => {});
},
好了,大功告成!
但是第二天就被测试小姐姐喊去
测试小姐姐:为什么这里有页pdf是空白的呀…?
我(一脸懵逼):这种不是后端返回的pdf就是长这样么(炒鸡自信)?
然后测试小姐姐一顿输出操作拉满,终于找到了后端接口返回的pdf,浏览器打开一看,嗯?我又懵了,果然不一样!!
go!来活了
本地调试发现控制台报以下错误~~
Uncaught (in promise) Error: Cannot use the same canvas during multiple render() operations. Use different canvas or ensure previous operations were cancelled or completed.
遇到问题不要急,先百度…然鹅,一天过去了…各种修改都无用…
最后跟大佬一起看发现原因是canvas重复渲染了,原来pdf.js里面for循环跟我的v-for渲染重复了
决定修改如下代码:
//html
//key值修改
<canvas
class="contract-canvas"
:ref="`contractCanvas${index + 1}`"
v-for="(_, index) in pageArray"
:key="`a${_.index}`"
></canvas>
>//js
>//nextSnowflakeId是snowflakeGenerator插件封装的方法,可以随机生成唯一id。
>this.pageArray = Array(pdf.numPages).fill({}).map(() => ({ index: nextSnowflakeId() }));
然后再运行,好啦!!不会再出现了,落班~~