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.
[button url=”http://codepen.io/bassta/full/OPVzyB/” style=”green” size=”large” type=”square” icon=”view” target=”_blank”]VIEW DEMO [/button] [button url=”http://codepen.io/bassta/pen/OPVzyB” type=”square” icon=”link” target=”_blank”] FORK AT CODEPEN [/button]
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 = $("", { "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!