Reputation: 11986
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.
Upvotes: 2
Views: 26941
Reputation: 63802
Alnitak's method is one way, but just to add more information you should be aware that setting the width also resets all canvas state. That means that you'll have to set your fonts, styles, line width, etc again. For performance reasons it can be good to cache these (not change them unless you absolutely have to, especially font
, which is slow to set) so doing canvas.width = canvas.width
is not always ideal.
There is of course
ctx.clearRect(0, 0, canvas.width, canvas.height);
But this won't help you much if you have a complex transformation matrix. If that is the case, you can always temporarily reset the transformation matrix by doing the following:
// I have lots of transforms right now
ctx.save();
ctx.setTransform(1, 0, 0, 1, 0, 0);
// Will always clear the right space
ctx.clearRect(0, 0, canvas.width, canvas.height);
ctx.restore();
// Still have my old transforms
Upvotes: 2
Reputation: 339786
You should be using the .width
of the canvas element, not its context.
There is no .width
property in the context, so your .clearRect
call is effectively being passed zero for its last two parameters.
Likewise, adding a new .width
property to the context won't do anything.
Just do this
var canvas = $('#canvas')[0]; // or document.getElementById('canvas');
canvas.width = canvas.width;
as described in the specifications (my emphasis):
When the canvas element is created, and subsequently whenever the width and height attributes are set (whether to a new value or to the previous value), the bitmap and any associated contexts must be cleared back to their initial state and reinitialized with the newly specified coordinate space dimensions.
Note that .clearRect()
will take any clipping path and fill styles into account, so setting the width
attribute 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!
Upvotes: 14