far*_*raz 5 html5-canvas reactjs
我在反应中使用画布,并使用画布将 pdf 渲染为图像。
现在,当我获得新数据时,即添加了另一个 pdf 文件,然后又必须为此使用画布。
我不知道如何修复这个错误,或者如何在再次使用之前删除画布甚至清除画布。
这是相关的代码:
pdfLoop = (item,index) => {
var that = this;
PDFJS.getDocument(item).then(function getPdfHelloWorld(pdf) {
//
// Fetch the first page
console.log('url is : ',item);
pdf.getPage(1).then(function getPageHelloWorld(page) {
var scale = 0.5;
var viewport = page.getViewport(scale);
let cref = 'canvas'+index;
let imgref ='img'+index;
console.log('cref no : ',cref);
console.log('img no : ',imgref);
// Prepare canvas using PDF page dimensions
//
var canvas = that.canvasRefs[cref];
//let imagez = that.imageRefs[imgref];
var context = canvas.getContext('2d');
context.globalcompositeoperation = 'source-over';
// context.fillStyle = "#fff";
//draw on entire canvas
//context.fillRect( 0, 0, canvas.width, canvas.height );
canvas.height = viewport.height;
canvas.width = viewport.width;
//imagez.src = canvas.toDataURL("image/png");
//
// Render PDF page into canvas context
//
//page.render({canvasContext: context, viewport: viewport});
var task = page.render({canvasContext: context, viewport: viewport})
task.promise.then(function(){
//console.log(canvas.toDataURL('image/png'));
let imgItem = {imgref:canvas.toDataURL('image/png'),page:index+1,rotate:0}
let newState = that.state.imgsrc;
newState[index] = imgItem;
//let newState = that.state.imgsrc.concat(imgItem);
that.setState({
imgsrc:newState
});
//imagez.src = canvas.toDataURL('image/png')
});
});
});
}
Run Code Online (Sandbox Code Playgroud)
如果有人偶然发现这一点,错误消息会显示以下内容Use different canvas or ensure previous operations were cancelled or completed.
当获取文件时,如果已有文件,则必须将其销毁。IE:
PDFJS.getDocument({ url: pdf_url }).promise
.then((pdf_doc) => {
if (this.pdf_doc) {
this.pdf_doc.destroy();
}
this.pdf_doc = pdf_doc;
this.total_pages = this.pdf_doc.numPages;
})
Run Code Online (Sandbox Code Playgroud)
我不知道这是否是一个好的解决方案,但至少它对我有用。
我在使用PDF.js时遇到了完全相同的问题,解决方案是,您必须在渲染完成后清除上下文。
if (context) {
context.clearRect(0, 0, canvas.width, canvas.height);
context.beginPath();
}
Run Code Online (Sandbox Code Playgroud)
这将确保上下文被清除并为下一次渲染做好准备,并且错误消失。
这对我有用。