Yury Shapkarin
Yury Shapkarin

Reputation: 519

Fit image to canvas by width and fit canvas to image new height

How to fit image that bigger that canvas width to canvas(with scale) and then to fit canvas to image height after fit by width.

Upvotes: 1

Views: 3161

Answers (1)

James Hunt
James Hunt

Reputation: 2528

// Create a variable for the canvas and it's context
var canvas = document.getElementById("imageCanvas");
var ctx = canvas.getContext("2d");

// Initialise an image object
var image = new Image();

// When it loads an image
image.onload = function() {
  // Get the canvas' current style
  var canvasStyle = getComputedStyle(canvas);
  
  // Get it's current width, minus the px at the end
  var canvasWidth = canvasStyle.width.replace("px", "");
  
  // Work out the images ratio
  var imageRatio = this.width/this.height;
  
  // Work out the new height of the canvas, keeping in ratio with the image
  var canvasHeight = canvasWidth/imageRatio;
  
  // Set the canvas' height in the style tag to be correct
  canvas.style.height = canvasHeight+"px";
  
  // Set the width/height attributes to be correct (as this is what drawImage uses)
  canvas.width = canvasWidth;
  canvas.height = canvasHeight;
  
  // Draw the image at the right width/height
  ctx.drawImage(this, 0, 0, canvasWidth, canvasHeight);
};

// Load an image
image.src="https://placekitten.com/g/600/800";
#imageCanvas
{
  width: 400px;
  height: 400px;
}
<canvas id="imageCanvas" width="400px" height="400px"></canvas>

There you go, shrinks the image to the right width, resizes canvas to the right height. Hopefully the comments explain everything.

Upvotes: 3

Related Questions