canvas resize awesomeness from math dude

by Nick Hulea

HTML

<body onload="initPage();">
    </body>

CSS

body { overflow: hidden; width:100%; height:100%; }
* { margin:0; padding:0; }
canvas { display:block; }

JavaScript

var vGap = 0;
var hGap = 0;

function writeSizeInfoToConsole(){
    var cw = ctx.canvas.width;
    var ch = ctx.canvas.height;
    var cssW = $(ctx.canvas).css("width");
    var cssH = $(ctx.canvas).css("height");
    var txt1 = "canvas: (w, h) = (" + cw + ", " + ch + ")"; 
    var txt2 = "css: (w, h) = (" + cssW + ", " + cssH + ")"; 
    console.log(txt1 + "     " + txt2);
}

var modes = {
    resizeByWidth: {
        description: "resize by width",
        afterInitCallback: function(){
            $(ctx.canvas).css("width", "100%");
        },
        windowResizeCallback: function(){
            // if you want to resize keeping aspect ratio the same and width 100%, you do not need to
            // do anything on window resize. This handler is attached for the sole purpose of writing 
            // some info to the console, so you can see what is going on.
            writeSizeInfoToConsole();
        }
    },
    messWithAspectRatio: {
        // keep both width and height to 100%, without using the canvas context to redraw
        // this necessarily messes up the aspect ratio
        description: "mess with aspect ratio",
        afterInitCallback: function(){
            $(ctx.canvas).css("width", "100%");
        },
        windowResizeCallback: function(){
            $(ctx.canvas).css("height", window.innerHeight - vGap);
            writeSizeInfoToConsole();
        }
    },
    fixed: {
        // the default is to keep width and height constant (no change on window resize)
        description: "default behaviour"
    },
    redraw: {
        // redraw the picture.
        // if you want to have 100% width and height, no matter what the aspect ratio is,
        // and a slightly different picture, depending on that aspect ratio
        // you have no other choice than to redraw the canvas.
        // If you rather want the aspect ratio to be constant, and do the thing outlined in "resizeByWidth" instead,
        // you will probably want to avoid...