drawImage - 调整大小并保持比例

时间:2017-09-20 08:14:27

标签: javascript html css drawimage

我正在尝试使用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>

我试图让图像填充容器以丢失底部的空白区域,如果我将精确的尺寸放入其中则会变得拉伸。

有没有人有一个例子可以指出我的方向?

1 个答案:

答案 0 :(得分:2)

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

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