(1) - StackOverflow_17377952: How to re-size canvas and draw image on canvas as perspective window size

Illustration of answer to: http://stackoverflow.com/questions/17377952/how-to-re-size-canvas-and-draw-image-on-canvas-as-perspective-window-size

HTML

<canvas id="canvas" width=210 height=261></canvas>

CSS

body {
    background-color: ivory;
    margin:0;
    overflow:hidden;
}
canvas {
    border:1px solid red;
}

JavaScript

var canvas = document.getElementById('canvas');
    var context = canvas.getContext('2d');

    // this function fill an image on canvas
    function drawImage(image) {
        context.drawImage(image, 0, 0, image.width, image.height, 0, 0, canvas.width, canvas.height);
    }

    var imageObj = new Image();
    imageObj.onload = function () {
        drawImage(this);
    };
    imageObj.src = "https://www.w3schools.com/howto/img_fjords.jpg";

    // set this to false to maintain the canvas aspect ratio, or true otherwise
    var stretch_to_fit = false;

    function resize() {
        // aspect ratio
        var widthToHeight = canvas.width / canvas.height;
        var newWidthToHeight = widthToHeight;

        // cache the window dimensions (discount the border)
        var newWidth = window.innerWidth - 2,
            newHeight = window.innerHeight - 2;

        if (stretch_to_fit) {
            // overwrite the current canvas aspect ratio to fit the entire screen
            widthToHeight = window.innerWidth / window.innerHeight;
        } else {
            newWidthToHeight = newWidth / newHeight;
        }

        // scale the canvas
        if (newWidthToHeight > widthToHeight) {
            newWidth = newHeight * widthToHeight;
            canvas.height = newHeight;
            canvas.width = newWidth;
        } else {
            newHeight = newWidth / widthToHeight;
            canvas.width = newWidth;
            canvas.height = newHeight;
        }

    };

    // listen to resize events
    window.addEventListener('resize', function () {
        // resizes the canvas (this will clear the canvas because the width and height parameters are changed).
        resize();
        // so, we need to redraw the image back on canvas
        drawImage(imageObj);
    }, false);

    // also resize the screen on orientation changes
    window.addEventListener('orientationchange', function () {
        resize();
        drawImage(imageObj);
    }, false);

    //...