I’m trying to implement a clear button but it doesn’t seem to be working.
I have an array of x, y, and drag positions along with the associated colors. When the clear button is pressed (and it is, I checked with an alert box), I am clearing all of these arrays and then clearing the canvas like so:
clickX.length = 0;
clickY.length = 0;
clickDrag.length = 0;
clickColor.length = 0;
var context = $('#canvas')[0].getContext('2d');
context.width = context.width;
context.height = context.height;
I heard setting the width and height may be slower so I always tried:
context.clearRect(0, 0, context.width, context.height);
However, none of these seem to be working. The arrays are emptied but the prior contents of the canvas just remain stuck there. Not sure why they aren’t being cleared.
Thanks for reading.
You should be using the
.widthof the canvas element, not its context.There is no
.widthproperty in the context, so your.clearRectcall is effectively being passed zero for its last two parameters.Likewise, adding a new
.widthproperty to the context won’t do anything.Just do this
as described in the specifications (my emphasis):
Note that
.clearRect()will take any clipping path and fill styles into account, so setting thewidthattribute is the only way to completely reset a canvas back to its original state. If you haven’t used clipping paths then.clearRect()may well be faster, though!