【问题标题】:How to destroy / reload the canvas in html 5?如何在 html 5 中销毁/重新加载画布?
【发布时间】:2013-08-29 15:40:24
【问题描述】:

我正在开发一个电子书应用程序,我使用 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 ,它们有必要吗?谢谢

【问题讨论】:

    标签: javascript jquery html canvas html5-canvas


    【解决方案1】:

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

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

    var oldcanv = document.getElementById('canvas');
    document.removeChild(oldcanv)
    
    var canv = document.createElement('canvas');
    canv.id = 'canvas';
    document.body.appendChild(canv);
    

    请注意,如果您打算保留多个,则每个都必须有一个唯一的 id 而不仅仅是 id="canvas"(可能基于页码 - 类似于 canvas-1)。


    更新问题的答案

    savesetTransformrestore 仅在您正在执行(或以某种方式允许用户执行)转换时才需要。我不知道 PDF.js 库是否在幕后进行了任何转换,因此最好将其留在那里。

    【讨论】:

    • 如果我使用 "$('#canvas').remove()" 删除画布并附加 $('body').prepend('');,有什么问题吗?谢谢
    • @user782104 是的,应该做同样的事情。
    • 如果你删除了画布,你不应该这样做clearRect,因为你正在摆脱整个事情。
    • 感谢您的帮助,请查看更新后的功能
    • 谢谢,看来重用和破坏只是简单地删除或附加它
    【解决方案2】:

    尝试使用clearRect(),例如:

    canvas = document.getElementById('canvas');
    ctx = canvas.getContext('2d');
    ctx.clearRect(0, 0, canvas.width, canvas.height);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-12-09
      • 1970-01-01
      • 1970-01-01
      • 2020-07-04
      • 2023-03-15
      • 2020-09-18
      相关资源
      最近更新 更多