如何在html 5中销毁/重新加载画布?

use*_*104 10 javascript jquery html5 canvas html5-canvas

我正在开发一个电子书应用程序,我使用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);
            });
        });
    });
}
Run Code Online (Sandbox Code Playgroud)

那么,在重绘页面之前是否需要执行任何必要的步骤?另外,如果我要关闭页面,我怎么能破坏它呢?谢谢

更新:

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
}
Run Code Online (Sandbox Code Playgroud)

我发现了一个清除画布的功能但除了clearRect之外它还有.save,.setTransform和.restore,它们是否必要?谢谢

Mos*_*atz 14

一种方法是使用context.clearRect(0,0, width, height)(参考)清除画布.

或者,您可以在每次需要新页面时附加新的画布元素(并可能删除旧的画布元素,具体取决于您是否要再次显示它).这样的事情应该这样做:

var oldcanv = document.getElementById('canvas');
document.removeChild(oldcanv)

var canv = document.createElement('canvas');
canv.id = 'canvas';
document.body.appendChild(canv);
Run Code Online (Sandbox Code Playgroud)

请注意,如果您计划保留多个,则每个人必须具有唯一id而不仅仅是id="canvas"(可能基于页码 - 类似的东西canvas-1).


回答更新的问题:

save,setTransform以及restore是只需要如果你正在做(或在某种程度上允许用户做)的转变.我不知道PDF.js库是否在幕后进行任何转换,因此最好将其保留在那里.


Sud*_*oti 9

尝试使用clearRect(),如:

canvas = document.getElementById('canvas');
ctx = canvas.getContext('2d');
ctx.clearRect(0, 0, canvas.width, canvas.height);
Run Code Online (Sandbox Code Playgroud)