JS-Center Image element inside the canvas

I scale the image down so that it fits inside the canvas, what I try my best to do is then center it inside the canavas element, does anyone know how to do this, 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); }; 
+5
source share
3 answers

  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" /> 
+4
source

A solution that will work both horizontally and vertically.

First find a scale that is the smallest scale to fit the width or height

 var scale = Math.min(canvas.width / img.width, canvas.height / img.height); 

Use this scale to get img width and height

 var w = img.width * scale; var h = img.height * scale; 

Then use this scale to calculate the upper left corner at half the distance from the center.

 var left = canvas.width / 2 - w / 2; var top = canvas.height / 2 - h / 2; 
+2
source

Passersby's solution works fine if you want something similar to object-fit: contain

This solution works great if you want object-fit: cover

 const fitImageToCanvas = (image,canvas) => { const canvasContext = canvas.getContext("2d"); const ratio = image.width / image.height; let newWidth = canvas.width; let newHeight = newWidth / ratio; if (newHeight < canvas.height) { newHeight = canvas.height; newWidth = newHeight * ratio; } const xOffset = newWidth > canvas.width ? (canvas.width - newWidth) / 2 : 0; const yOffset = newHeight > canvas.height ? (canvas.height - newHeight) / 2 : 0; canvasContext.drawImage(image, xOffset, yOffset, newWidth, newHeight); }; 
0
source

All Articles