Cogitas Blog:
Google Android,
Common Lisp,
programming
and web design.

How to reset canvas in HTML5

Filed under: web — Tags: , — August 24, 2010

The excellent “Dive Into HTML5″ online tutorial by Mark Pilgrim mentions that to reset a canvas (= clear all its contents), all you need to do is set its width. It even says that you can set the width to be the same as the current width and gives the example below

var b_canvas = document.getElementById("b");
b_canvas.width = b_canvas.width;

Well, this doesn’t seem to work in Google Chrome 6.0.472.25 dev version. After trial and error, it seems that the only way to reset the canvas with the width method is to actually give it a different width as follows

myCanvas = document.getElementById("myCanvas");
var width = myCanvas.width;
myCanvas.width = width + 1;

Of course, the problem with that is that you find yourself increasing the size of your canvas, so to keep a canvas of the same size, simply add the following (after the code above)

width = myCanvas.width;
myCanvas.width = width - 1;

While it seems to work, it’s a hack I’m not satisfied with – anybody else has come across the same situation? How do you reset your HTML5 canvas?  Is it a bug in Google Chrome Dev (this is after all an unstable version of Google Chrome by definition)?

Related posts

Freelance Jobs


4 Comments »

  1. Until a chrome bug fix, this is working for me:
    c.width–;
    c.width++;

    Comment by Alberto — August 25, 2010 @ 12:31 am

  2. I ran into the same thing. Guess we’ll use Alberto’s suggestion. I use:
    c.width++;
    c.width–;

    Comment by Ronny — September 26, 2010 @ 8:31 am

  3. The double minusus are being eaten by the Wordpress, but believe me they’re there ;-)

    Comment by Ronny — September 26, 2010 @ 9:33 am

  4. My solution for clearing the HTML5 Canvas for all of the browsers is here: http://www.html5canvastutorials.com/articles/html5-clear-canvas/

    @Eric Rowell : Comment edited: I have replaced “Best solution” with “My solution” because you are the author of the blog article you are linking to so the “best” qualitative is self-referential and “my” is therefore more appropriate.

    Comment by Eric Rowell — December 19, 2010 @ 8:42 pm

RSS feed for comments on this post. TrackBack URL

Leave a comment