1

Hi I'm doing a drawing app using canvas but i dunno how to clear canvas. I've tried clearRect and other functions but they don't work. The last two function of the script should clear canvas but they don't work... (sorry for my bad english) Here the code:

  function clear_canvas_width ()
      {
            var s = document.getElementById ("scribbler");
            var w = s.width;
            s.width = 10;
            s.width = w;
        }

        function clear_canvas_rectangle ()
        {
               var canvas = $('#canvas')[0]; // or document.getElementById('canvas');
               canvas.width = canvas.width;
         }
Cheran Shunmugavel
  • 7,899
  • 1
  • 28
  • 39
  • possible duplicate of [How to clear the canvas for redrawing](http://stackoverflow.com/questions/2142535/how-to-clear-the-canvas-for-redrawing) – Prestaul Jul 01 '14 at 19:10

3 Answers3

4

Need a bit more code to really see what the problem is. Here is something really simple that you can go off of to maybe narrow it down. Also for performance reasons its better to use clearRect over resetting the width of the canvas. How you clear your canvas matters

Live Demo

var clearBut = document.getElementById("clearCan"),
    canvas = document.getElementById("canvas"),
    ctx = canvas.getContext("2d");


canvas.width = canvas.height = 300;
ctx.fillRect(10,10,280,280);


function clearCanvas(){
    ctx.clearRect(0,0,canvas.width, canvas.height);        
}

clearBut.addEventListener("click", clearCanvas);

Loktar
  • 32,547
  • 8
  • 83
  • 101
0

Have you checked whether you are clearing the right canvas? Maybe if you provide us with more code we can help you further.

Also make sure you don't draw over it after you have cleared it.

However, when it comes to clearing canvases this is the easiest way I know.

function clear_canvas( canvas ){
    canvas.width = canvas.width;
}

But you can also use

function clear_canvas (ctx, canvas){
    ctx.clearRect(0, 0, canvas.width, canvas.height); 
}
Vlad Otrocol
  • 2,214
  • 6
  • 27
  • 51
0

from;

How to clear the canvas for redrawing

// 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();
Community
  • 1
  • 1
fuzzy dunlop
  • 478
  • 1
  • 10
  • 22