Admamza Admamza - 2 months ago 7
Javascript Question

JS - Center Image inside canvas element

I'm scaling the image down so it fits inside the canvas, the thing I am struggling to do is to then center it inside of the canavas element, does anyone know how this could be done please? Any help would be appreciated

https://jsfiddle.net/n7xL5c37/

var canvas = document.getElementById('canvas');
var image = new Image();
image.src = 'http://placehold.it/300x550';
image.onload = function () {
var canvasContext = canvas.getContext('2d');
var wrh = image.width / image.height;
var newWidth = canvas.width;
var newHeight = newWidth / wrh;
if (newHeight > canvas.height) {
newHeight = canvas.height;
newWidth = newHeight * wrh;
}

canvasContext.drawImage(image,0,0, newWidth , newHeight);
};

Answer

    var canvas = document.getElementById('canvas');
    var image = new Image();
    image.src = 'http://placehold.it/300x550';
    image.onload = function () {
        var canvasContext = canvas.getContext('2d');
        var wrh = image.width / image.height;
        var newWidth = canvas.width;
        var newHeight = newWidth / wrh;
        if (newHeight > canvas.height) {
					newHeight = canvas.height;
        	newWidth = newHeight * wrh;
      	}
        var xOffset = newWidth < canvas.width ? ((canvas.width - newWidth) / 2) : 0;
        var yOffset = newHeight < canvas.height ? ((canvas.height - newHeight) / 2) : 0;

      	canvasContext.drawImage(image, xOffset, yOffset, newWidth, newHeight);
      };
<canvas id="canvas" width="500" height="500" style="border: 1px solid black" />