HTML5 responsive canvas: resizing the browser canvas draw disappear

Dealing with contents when resizing a canvas

If you resize the canvas, the drawn content is always erased. That’s how canvas behaves.

You can either redraw the content after resizing or you can save the content as image data and restore after resizing (see canvas.toDataURL).

Here is code and a Fiddle: http://jsfiddle.net/m1erickson/V6SVz/

<!doctype html>
<html>
<head>
<link rel="stylesheet" type="text/css" media="all" href="https://stackoverflow.com/questions/15878377/css/reset.css" /> <!-- reset css -->
<script type="text/javascript" src="http://code.jquery.com/jquery.min.js"></script>

<style>
    body{ background-color: ivory; padding:10px; }
    canvas{border:1px solid red;}
</style>

<script>
$(function(){

    var canvas=document.getElementById("canvas");
    var ctx=canvas.getContext("2d");

    // draw some content
    ctx.lineWidth=3;
    ctx.fillStyle="blue";
    ctx.strokeStyle="red";
    ctx.rect(50,50,100,50);
    ctx.fill();
    ctx.stroke();
    ctx.font="14px Verdana";
    ctx.fillStyle="white";
    ctx.fillText("Scale Me",65,75);

    function saveResizeAndRedisplay(scaleFactor){

        // save the canvas content as imageURL
        var data=canvas.toDataURL();

        // resize the canvas
        canvas.width*=scaleFactor;
        canvas.height*=scaleFactor;

        // scale and redraw the canvas content
        var img=new Image();
        img.onload=function(){
            ctx.drawImage(img,0,0,img.width,img.height,0,0,canvas.width,canvas.height);
        }
        img.src=data;

    }

    $("#resizer").click(function(){ saveResizeAndRedisplay(1.5); });

}); // end $(function(){});
</script>

</head>

<body>
    <button id="resizer">Click to resize the canvas</button><br/>
    <canvas id="canvas" width=200 height=150></canvas>
</body>
</html>

Leave a Comment