JS - Center Image inside canvas element

A solution that will work for both horizontal and vertical.

First find the scale which is the min scale to fit the width or height

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

Use that scale to get the img width and height

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

Then use that scale to calculate the top left as half the dist from the center

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

Solution of Passersby works fine if you want something similar to object-fit: contain

This solution works fine 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);
};

    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" />