How to clear an HTML canvas?

canvas, html, jquery

Solution

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!

Problem

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.

Original source