drawImage - 调整大小并保持比例

drawImage - Resize and keep scale

我正在尝试使用 drawImage 调整图像大小但保持比例不变。到目前为止我有这个...

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>

我试图让图像填满容器以去掉底部的白色 space,如果我放入准确的尺寸,它就会被拉伸。

有没有人可以举个例子来指导我?

首先您需要找到图像和 canvas 的纵横比。这是通过以下方式完成的:

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

如果比率小于 1,则为纵向,否则如果等于或大于 1,则为(视为)横向。

然后你需要像这样比较这些比率:

//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(…);

更新

这样更短(没有比率,没有if):

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

要适合图像使用 Math.min