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;
source share