1

Probably I'm missing something fundamental.

I'm filling a canvas with objects. On user input I need to resize the canvas (thus scaling the content).

JS (simplified):

var c = document.getElementById('c');
var cc = c.getContext('2d');
cc.beginPath();        
cc.rect(20, 20, 20, 12);
cc.fill();

function resizeCanvas(size){
    var c = document.getElementById('c');
    var cc = c.getContext('2d');
    // This will make the content disappear
    c.width = c.style.width = c.height = c.style.height = size;
}

HTML

<canvas id="c" width="200" height="200"></canvas>
<br/>
<button onclick='resizeCanvas(100);return false;'>Resize</button>

CSS

canvas {border: 1px solid black}

The canvas is resized but the content is blanked. Any idea?

jsfddle here

Stefano Altieri
  • 4,550
  • 1
  • 24
  • 41

1 Answers1

1

By changing either width or height -and obviously by changing both-, you completely redefine the canvas, so in fact it is quite logical that the canvas content is cleared : how should it change ?
Should it scale ? , re-use existing pixels values, but how ? centered, ... ??

That was even a 'trick' at some time : to clear a canvas, just do canvas.width = 0 then canvas.width = oldWidth , and that will clear things up. Since clearRect or fillRect are now faster that this trick, it has no reason to be used any more.

So when your canvas get resized, it will get cleared. It's up to you to decide of the policy you want when such resize occur : will you scale old canvas and copy it on the new one, or copy at same scale centered, or will that be an up/left most copy ??
you decide.

If you have a 'scene graph', meaning : if you are able to redraw every objects of your canvas, there's no real issue.
If you don't, you have to do some efforts to get the old content on the new canvas.
Something like (untested) :

function resizeCanvas(size){
    var c = document.getElementById('c');
    var canvasCopy = document.createElement('canvas');
    canvasCopy.width = c.width; canvasCopy.height = c.height;
    canvasCopy.getContext('2d').drawImage(c, 0,0 ); // copy the 'old' canvas
    // This will make the content disappear
    c.width = c.style.width = c.height = c.style.height = size;
    var cc = c.getContext('2d');
    cc.drawImage(canvasCopy, 0, 0) ;  // or you might scale, or center, or...
}
GameAlchemist
  • 18,995
  • 7
  • 36
  • 59