HTML canvas - drawing disappear on resizing

2019-02-12 10:25发布

问题:

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

回答1:

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/



回答2:

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


回答3:

I also met this problem.but after a experiment, I found that Resizing the canvas element will automatically clear all drawings off the canvas! just try the code below

<canvas id = 'canvas'></canvas>
<script>
    var canvas1 = document.getElementById('canvas')
    console.log('canvas size',canvas1.width, canvas1.height)
    var ctx = canvas1.getContext('2d')
    ctx.font = 'Bold 48px Arial'
    var f = ctx.font
    canvas1.width = 480
    var f1 = ctx.font
    alert(f === f1) //false
</script>


回答4:

I had the same problem. Try following code

var wrapper = document.getElementById("signature-pad");
var canvas = wrapper.querySelector("canvas");
var ratio = Math.max(window.devicePixelRatio || 1, 1);
canvas.width = canvas.offsetWidth * ratio;
canvas.height = canvas.offsetHeight * ratio;

It keeps the drawing as it is