HTML5 Canvas Does Not Clear

I use all possible methods to clean the canvas, but not good luck. As soon as I click on the canvas, all previous drawings reappear.

Here is the code.

function clearCanvas() { //clickX = []; //clickY = []; //clickDrag = []; //context.clearRect(0, 0, canvas.width, canvas.height); //curColor = colorBlack; //redraw(); //clickX = new Array(); //clickY = new Array(); //clickDrag = new Array(); context.fillStyle = '#faebd7'; context.fillRect(0, 0, canvas.width, canvas.height); canvas.width = canvas.width; //context.beginPath(); }; 
+4
source share
3 answers

It seems to me that you use Arrays to store information about drawings. I see you tried cleaning them, but as far as I know, the best way to clean them is to set the length to zero. Try the following:

 function clearCanvas() { clickX.length = 0; clickY.length = 0; clickDrag.length = 0; context.clearRect(0, 0, canvas.width, canvas.height); }; 
+2
source

If it does not clean (and you have no errors), then

  • Your clearCanvas() method is not being entered or
  • You redraw on the canvas AFTER your clearCanvas() call.

Sorry, the best I got with the information available: P

+1
source

You say, "As soon as I click on the canvas." Does this mean that the canvas is first cleaned until you click on it? Then it tells me that you have an event handler that redraws anything.

Also, make sure your context is still pointing to the correct canvas. Several canvases require the creation of a temporary canvas. If you did this, you might be clearing the wrong context. Otherwise, I do not understand why context.clearRect will not work the way you do.

+1
source

Source: https://habr.com/ru/post/1437902/


All Articles