How to clear the canvas for redrawing

后端 未结 23 2816
粉色の甜心
粉色の甜心 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条回答
  • 2020-11-21 12:24

    Given that canvas is a canvas element,

    const context = canvas.getContext('2d');
    
    context.clearRect(0, 0, canvas.width, canvas.height);
    
    0 讨论(0)
  • 2020-11-21 12:25

    This is what I use, regardless boundaries and matrix transformations:

    function clearCanvas(canvas) {
      const ctx = canvas.getContext('2d');
      ctx.save();
      ctx.globalCompositeOperation = 'copy';
      ctx.strokeStyle = 'transparent';
      ctx.beginPath();
      ctx.lineTo(0, 0);
      ctx.stroke();
      ctx.restore();
    }
    

    Basically, it saves the current state of the context, and draws a transparent pixel with copy as globalCompositeOperation. Then, restores the previous context state.

    0 讨论(0)
  • 2020-11-21 12:25
    function clear(context, color)
    {
        var tmp = context.fillStyle;
        context.fillStyle = color;
        context.fillRect(0, 0, context.canvas.width, context.canvas.height);
        context.fillStyle = tmp;
    }
    
    0 讨论(0)
  • 2020-11-21 12:26

    A quick way is to do

    canvas.width = canvas.width
    

    Idk how it works but it does!

    0 讨论(0)
  • 2020-11-21 12:26
    Context.clearRect(starting width, starting height, ending width, ending height);
    

    Example: context.clearRect(0, 0, canvas.width, canvas.height);

    0 讨论(0)
提交回复
热议问题