简体   繁体   中英

Clear function on Canvas isnt working properly

When you click the Clear Canvas button on codepen, it will appear as if the canvas is cleared but if you try drawing again, all the old lines will re-appear.

//Redraw
function redraw(){
    $("#clearcanvas").click(function () {
      context.clearRect(0, 0, context.canvas.width, context.canvas.height); 
    });
    context.strokeStyle = "#df4b26";
    context.lineJoin = "round";
    context.lineWidth = 5;

    for(var i=0; i < clickX.length; i++) {      
      context.beginPath();
      if(clickDrag[i] && i){
        context.moveTo(clickX[i-1], clickY[i-1]);
      }
      else {
        context.moveTo(clickX[i]-1, clickY[i]);
      }
      context.lineTo(clickX[i], clickY[i]);
      context.closePath();
      context.stroke();
  }   
}

Full code: http://codepen.io/urketadic/pen/AXGKvp

The old lines are re-appearing because they're stored in clickX and in clientY , and when you basically draw in the canvas you call redraw method in your code, which draw everything in these objects. You're missing to clear both of these objects.

(I've forgot one, clickDrag .)

To clear a array (such object) without losing its references, just set its 'length' property to 0 .

clientX.length =
clientY.length =
clickDrag.length = 0

Because you are storing the information for each drawn line inside a arrays being clickX , clickY , and clickDrag . The canvas will draw each of those lines over even after you clear the canvas. What you will want to do is empty those array items:

$("#clearcanvas").click(function () {
   context.clearRect(0, 0, context.canvas.width, context.canvas.height); 
   clickX = []; clickY = []; clickDrag = []; // or 'new Array()' or '.length = 0'
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM