Dynamically resize canvas window with javascript/jquery?

canvas, html, javascript, jquery

Solution

Make a function that does the drawing, then re-draw whenever something changes that requires it (like a page resize, etc). Try it out

Make sure you set the context.canvas.width/height, not CSS width/height. Also note that setting the size clears the canvas.

How I would write it:

(function(){
    var c = $("#canvas"), 
        ctx = c[0].getContext('2d');

    var draw = function(){
        ctx.fillStyle = "#000";
        ctx.fillRect(10,10,50,50);   
    };

    $(function(){
        // set width and height
         ctx.canvas.height = 600;
         ctx.canvas.width = 600;
        // draw
        draw();

        // wait 2 seconds, repeate same process
        setTimeout(function(){
            ctx.canvas.height = 400;
            ctx.canvas.width = 400;
            draw();
        }, 2000)
    });
})();

Problem

How can I resize a canvas with javascript/jquery? Resizing using the css function and applying it to the canvas element just stretches the content as if you were stretching an image. How would I go about doing this without the stretching? http://jsfiddle.net/re8KU/4/

Original source

Related problems