0

I am trying to resize an image using drawImage but keep the scale. I have this so far...

window.onload = function() {
    var c = document.getElementById("myCanvas");
    var ctx = c.getContext("2d");
    var img = document.getElementById("scream");
    ctx.drawImage(img, 0, 0, 600, 428);
}
<p>Image to use:</p>
<img id="scream" width="400" height="300" src="http://lorempixel.com/1280/960/sports/" alt="The Scream">

<p>Canvas:</p>
<canvas id="myCanvas" width="428" height="600" style="border:2px solid black;">
Your browser does not support the HTML5 canvas tag.
</canvas>

I am trying to make the image fill the container to lose the white space at the bottom, if I put the exact dimensions in then it becomes stretched.

Does anyone have an example they can point me in the direction of?

fightstarr20
  • 11,682
  • 40
  • 154
  • 278
  • 1
    you mean keep the ratio? Like in https://stackoverflow.com/questions/21961839/simulation-background-size-cover-in-canvas or one of the options of https://stackoverflow.com/questions/34428723/? – Kaiido Sep 20 '17 at 08:17

1 Answers1

3

First you need to find the aspect ratios of the image and the canvas. That is done by:

var canvasRatio = canvas.width / canvas.height,
    imgRatio = img.width / img.height,
    s = 1;

If a ratio is less than 1, then it is portrait, else if it is equal or higher than 1, it is (considered to be) landscape.

Then you need to compare those ratios like so:

//the image is »more portrait«
//to fully cover the canvas
//scale by width
if (imgRatio < canvasRatio) {
  s = canvas.width / img.width;

//image has the same, or a »more landscape«
//ratio than the canvas
//to cover scale by height
} else {
  s = canvas.height / img.height;
}

//scale the context
ctx.scale(s, s);
cts.drawImage(…);

UPDATE

It is even shorter this way (no ratios, no if):

var s = Math.max(canvas.width/img.width, canvas.height/img.height);

to fit the image use Math.min.

philipp
  • 15,947
  • 15
  • 61
  • 106