Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

HTML canvas - drawing disappear on resizing

I have created a basic shape in HTML canvas element which works fine.

The problem occurs when I resize the canvas, all the drawing in the canvas disappears. Is this the normal behavior? or is there a function that can be used to stop this?

One way to fix this could be to call drawing function again on canvas resize however this may not be very efficient if there is huge content to be drawn.

What's the best way?

Here is the link to sample code https://gist.github.com/2983915

like image 963
Yogesh Agarwal Avatar asked Jun 24 '12 16:06

Yogesh Agarwal


People also ask

Does resizing a canvas clear it?

Resize it using CSS every time you resize with canvas. width, canvas. height the canvas is fully cleared. if you're building a drawing app you have probably defined a function to redraw the canvas every time a change is applied so use the same function to redraw the canvas after it changed.

How do you dynamically resize canvas?

Resizing the canvas on the fly is quite easy. To do it, simply set the width and height properties of the Canvas object, and then redraw the canvas contents: Canvas . width = 600 ; Canvas .

How do I make my canvas fit the screen in HTML?

Set the Size with CSSto set the canvas's width and height both to 100%. We also set the position to absolute and top , left , right , and bottom to 0 to make the canvas fill the screen. Also, we make the html and body elements fill the screen by setting the width and height to 100%.


2 Answers

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/

like image 62
Simon Sarris Avatar answered Oct 13 '22 18:10

Simon Sarris


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
like image 3
remcoder Avatar answered Oct 13 '22 17:10

remcoder