登录

javascript - 如何快速清除Canvas图形组合模式?

尝试Canvas组合图形功能后,想清除图形从新绘图。我该如何操作?每次都重绘新的矩形Canvas虽然有效,但并不是最好的办法,有没有更加简便实用的方法?

原问题:How to clear the canvas for redrawing

# JavaScript
PHPzPHPz2204 天前640 次浏览

全部回复(2) 我要回复

  • 数据分析师

    数据分析师2017-10-01 01:20:20

    javascript - 如何快速清除Canvas图形组合模式?-PHP中文网问答-javascript - 如何快速清除Canvas图形组合模式?-PHP中文网问答

    围观一下哦,学习一下。

    回复
    0
  • PHP中文网

    PHP中文网2017-04-10 13:13:13

    答案:
    Pentium10:

    context.clearRect ( x , y , w , h ); 
    or 
    canvas.width = canvas.width;Prestaul:
    
    ---
    
    Prestaul:
    

    一种方法是重置canvas.width和所有canvas状态(如transformations,lineWidth,strokeStyle等)。
    另一种更快捷的方法是使用ctx.clearRect(0,0,canvas.width,canvas.height)。如果你已经修改了变形矩阵,可能会导致清除不全。所以要优先重置变形矩阵状态:

    // Store the current transformation matrix
    ctx.save();
    // Use the identity matrix while clearing the canvas
    ctx.setTransform(1, 0, 0, 1, 0, 0);
    ctx.clearRect(0, 0, canvas.width, canvas.height);
    // Restore the transform
    ctx.restore();
    

    我在Chrome中做了一些分析,清除300x150(默认尺寸)的Canvas比重置矩形要快10%。随着Canvas尺寸的增大,所用的时间也会逐渐拉开差距。

    100000 iterations averaged 10 times:
    1885ms to clear
    2112ms to reset and clear
    

    trembl:如果你绘制了线条,不要忘记context.beginPath(); 否则线条清除不掉。


    JonathanK:别人已经提出了很好的解决方案,也许context.clear()方法对于你也会有用。

    CanvasRenderingContext2D.prototype.clear = 
      CanvasRenderingContext2D.prototype.clear || function (preserveTransform) {
        if (preserveTransform) {
          this.save();
          this.setTransform(1, 0, 0, 1, 0, 0);
        }
    
        this.clearRect(0, 0, this.canvas.width, this.canvas.height);
    
        if (preserveTransform) {
          this.restore();
        }           
    };
    
    Usage:
    
    window.onload = function () {
      var canvas = document.getElementById('canvasId');
      var context = canvas.getContext('2d');
    
      // do some drawing
      context.clear();
    
      // do some more drawing
      context.setTransform(-1, 0, 0, 1, 200, 200);
      // do some drawing with the new transform
      context.clear(true);
      // draw more, still using the preserved transform
    };
    

    orion elenzil:
    如果你想在原先的图片上添加点乐趣,只清除部分Canvas的话可以尝试”淡出“效果,这个很容易实现,仅需添加一个白色背景。

    // assuming background color = white and "eraseAlpha" is a value from 0 to 1.
    myContext.fillStyle = "rgba(255, 255, 255, " + eraseAlpha + ")";
    myContext.fillRect(0, 0, w, h);
    

    回复
    0
  • 取消回复发送