How to clear the canvas for redrawing

后端 未结 23 3266
粉色の甜心
粉色の甜心 2020-11-21 11:37

After experimenting with composite operations and drawing images on the canvas I\'m now trying to remove images and compositing. How do I do this?

I need to clear th

23条回答
  •  萌比男神i
    2020-11-21 12:19

    Others have already done an excellent job answering the question but if a simple clear() method on the context object would be useful to you (it was to me), this is the implementation I use based on answers here:

    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
    };
    

提交回复
热议问题