javascript - drawImage - 调整大小并保持比例

标签 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>

我试图让图像填满容器以减少底部的空白区域,如果我放入准确的尺寸然后它就会被拉伸(stretch)。

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

最佳答案

首先,您需要找到图像和 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 来适应图像。

关于javascript - drawImage - 调整大小并保持比例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46316742/

相关文章:

javascript - 根据同一表单中下拉菜单的值启用 HTML 表单文本框?

javascript - jquery 获取表单 DIV 的数据到 PHP $_POST

javascript - 返回上一页后图像不隐藏

html - 在 Bootstrap 中使用网格系统

javascript - 如何将变量传递给 CSS 网格 repeat() 函数

css - 我可以将 3 个元素布置到那个中间元素向左浮动吗?

html - 仅使用 css 在 div 上从 sprite 表中拉伸(stretch)图像的一部分

javascript - 解析字符串 : extracting words and phrases [JavaScript]

javascript - 我无法在 javascript 中从 firebase 中获取数据

html - 如何对齐 css 网格单元格中的元素?