我正在开发一个电子书应用程序,我使用 PDF.js 在画布上绘制每个页面,问题是,当我单击按钮并转到其他页面时,我尝试再次在同一画布上渲染,但画布似乎移动到错误的位置或错误的尺寸。
function renderPage(url) {
canvas = document.getElementById('canvas');
ctx = canvas.getContext('2d');
//clearCanvasGrid('canvas');
PDFJS.getDocument(url).then(function (pdf) {
// Using promise to fetch the page
pdf.getPage(1).then(function(page) {
var viewport = page.getViewport(5); //scale 5
canvas.height = viewport.height;
canvas.width = viewport.width;
// Render PDF page into canvas context
var renderContext = {
canvasContext: ctx,
viewport: viewport
};
page.render(renderContext).then(function() {
initialZoomPage(viewport.height,viewport.width);
});
});
});
}
那么,在重绘页面之前我需要做任何必要的步骤吗?另外,如果我想关闭页面,我该如何销毁它?谢谢
更新:
function clearCanvasGrid(canvasID){
canvas = document.getElementById(canvasID); //because we are looping //each location has its own canvas ID
context = canvas.getContext('2d');
//context.beginPath();
// Store the current transformation matrix
context.save();
// Use the identity matrix while clearing the canvas
context.setTransform(1, 0, 0, 1, 0, 0);
context.clearRect(0, 0, canvas.width, canvas.height);
// Restore the transform
context.restore(); //CLEARS THE SPECIFIC CANVAS COMPLETELY FOR NEW DRAWING
}
我找到了一个清除画布的函数,但除了 clearRect 之外,它还有 .save 、 .setTransform 和 .restore ,它们有必要吗?谢谢