How to clear the canvas for redrawing

后端 未结 23 2814
粉色の甜心
粉色の甜心 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:07

    fastest way:

    canvas = document.getElementById("canvas");
    c = canvas.getContext("2d");
    
    //... some drawing here
    
    i = c.createImageData(canvas.width, canvas.height);
    c.putImageData(i, 0, 0); // clear context by putting empty image data
    
    0 讨论(0)
  • 2020-11-21 12:09

    These are all great examples of how you clear a standard canvas, but if you are using paperjs, then this will work:

    Define a global variable in JavaScript:

    var clearCanvas = false;
    

    From your PaperScript define:

    function onFrame(event){
        if(clearCanvas && project.activeLayer.hasChildren()){
            project.activeLayer.removeChildren();
            clearCanvas = false;
        }
    }
    

    Now wherever you set clearCanvas to true, it will clear all the items from the screen.

    0 讨论(0)
  • 2020-11-21 12:12

    A simple, but not very readable way is to write this:

    var canvas = document.getElementId('canvas');
    
    // after doing some rendering
    
    canvas.width = canvas.width;  // clear the whole canvas
    
    0 讨论(0)
  • 2020-11-21 12:14

    I always use this

    ctx.clearRect(0, 0, canvas.width, canvas.height)
    window.requestAnimationFrame(functionToBeCalled)
    

    NOTE

    combining clearRect and requestAnimationFrame allows for more fluid animation if that is what you're going for

    0 讨论(0)
  • 2020-11-21 12:16

    This worked for my pieChart in chart.js

    <div class="pie_nut" id="pieChartContainer">
        <canvas id="pieChart" height="5" width="6"></canvas> 
    </div>
    
    $('#pieChartContainer').html(''); //remove canvas from container
    $('#pieChartContainer').html('<canvas id="pieChart" height="5" width="6"></canvas>'); //add it back to the container
    
    0 讨论(0)
  • 2020-11-21 12:16

    I have found that in all browsers I test, the fastest way is to actually fillRect with white, or whataever color you would like. I have a very large monitor and in full screen mode the clearRect is agonizingly slow, but the fillRect is reasonable.

    context.fillStyle = "#ffffff";
    context.fillRect(0,0,canvas.width, canvas.height);
    

    The drawback is that the canvas is no longer transparent.

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