HTML canvas - drawing disappear on resizing

Everytime you resize the canvas it will reset itself to transparant black, as defined in the spec.

You will either have to:

  • redraw when you resize the canvas, or,
  • don't resize the canvas

You need to redraw the scene when you resize.

setting the width or height of a canvas, even if you are setting it to the same value as before, not only clears the canvas but resets the entire canvas context. Any set properties (fillStyle, lineWidth, the clipping region, etc) will also be reset.

If you do not have the ability to redraw the scene from whatever data structures you might have representing the canvas, you can always save the entire canvas itself by drawing it to an in-memory canvas, setting the original width, and drawing the in-memory canvas back to the original canvas.

Here's a really quick example of saving the canvas bitmap and putting it back after a resize:

http://jsfiddle.net/simonsarris/weMbr/


One another way is to use the debounce if you are concerned with the performance. It doesnt resize or redraw every position you are dragging. But it will resize only when the it is resized.

 // Assume canvas is in scope
 addEventListener.("resize", debouncedResize );

 // debounce timeout handle
 var debounceTimeoutHandle;

 // The debounce time in ms (1/1000th second)
 const DEBOUNCE_TIME = 100; 

 // Resize function 
 function debouncedResize () { 
    clearTimeout(debounceTimeoutHandle);  // Clears any pending debounce events

 // Schedule a canvas resize 
 debounceTimeoutHandle = setTimeout(resizeCanvas, DEBOUNCE_TIME);
 }

 // canvas resize function
 function resizeCanvas () { ... resize and redraw ... }