Force a Canvas Refresh

When playing around with some canvas stuff I found an interesting bug in Chrome. Basically when you have a putImageData call inside of a setInterval loop, canvas does not refresh properly.

There’s a pretty simple hack to fix this: force the canvas to refresh every time you call putImageData. But how do you do this? There is no redraw function, nor any obvious way to force a refresh.

The trick is making a change to some property of the canvas element. Doing this in a way that forces a refresh every frame but won’t actually change anything for the user is not as obvious as you’d think.

Opacity isn’t actually visible with a sufficiently small delta, so it’s a good candidate. We just switch back and forth between two different opacities.

this.ctx.putImageData(img, x, y);
this.rebuild_chrome_hack = !this.rebuild_chrome_hack;
$('#canvas').css('background-color', this.rebuild_chrome_hack ? 1 : 0.999);

2 responses to “Force a Canvas Refresh”

  1. tom says:

    that may not be the greatest idea. changing opacity from 1.0 (even if not observably so) might trigger some other (possibly much slower) drawing mode in some other browser (on some other platform).

  2. Brian says:

    @tom: True, given that IE doesn’t have canvas support and I’m just going to fallback anyway, it seems like a good solution (tested in Gecko & Webkit).

    I originally used background color, but I needed the transparency. I’m sure there are other CSS options you can switch between, I’m just not sure what they are.

Leave a Reply