At a recent project, I needed to draw an image in canvas. The app had to be fullscreen, and the image should resize in the canvas proportionally. I searched for a code that does it, but couldn’t find any. Actually it’s not very hard to write piece of code that does it and today I will guide you how.

VIEW DEMO FORK AT CODEPEN

The flow is, we create a canvas, and load an image. Once the image is loaded, we get image dimensions and calculate image’s aspect ratio. Then, we calculate viewport’s aspect ratio. Once we know image and viewport dimensions and their aspect ratio’s the calculation is trivial.

 

var $window = $(window),
    $canvasHolder = $(".canvas__holder"),
    $canvas = $("#image__canvas"),
    canvas = $canvas.get(0),
    canvasContext = canvas.getContext("2d")

var winWidth, winHeight, winRatio, imgWidth, imgHeight, imgRatio, canvasInited;

var img;
var $img = $("<img alt="" />", {
    "src": "home.jpg" //link to your image
}).load(function() {

    img = $img.get(0);

    imgWidth = img.width;
    imgHeight = img.height;
    imgRatio = imgWidth / imgHeight;

    canvasInited = true;
    resizeCanvas();
});

$window.on("resize", onResize);
$window.trigger("resize");

function onResize() {
    winWidth = $window.width();
    winHeight = $window.height();
    winRatio = winWidth / winHeight;

    $canvas.attr({
        "width": winWidth + "px",
        "height": winHeight + "px"
    });

    $canvasHolder.add($canvas).css({
        "width": winWidth + "px",
        "height": winHeight + "px"
    });

    if (canvasInited) {
        resizeCanvas();
    }

}

function resizeCanvas() {

    var newWidth = winWidth,
        newHeight = winHeight,
        newX = 0,
        newY = 0;

    if (winRatio > imgRatio) {
        newHeight = Math.round(winWidth / imgRatio);
        newY = (winHeight - newHeight) / 2;
    } else {
        newWidth = Math.round(winHeight * imgRatio);
        newX = (winWidth - newWidth) / 2;
    }

    canvasContext.drawImage(img, newX, newY, newWidth, newHeight);

}

Voala, our image is centred in the canvas on every window resize!