【问题标题】:drawImage - Resize and keep scaledrawImage - 调整大小并保持比例
【发布时间】:2018-03-01 04:49:52
【问题描述】:

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

我试图让图像填充容器以丢失底部的空白区域,如果我放入确切的尺寸,那么它就会被拉伸。

有没有人可以为我指明方向的例子?

【问题讨论】:

标签: javascript html css drawimage


【解决方案1】:

首先,您需要找到图像和画布的纵横比。由以下人员完成:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-09-04
    • 1970-01-01
    • 2020-06-14
    • 1970-01-01
    • 2013-02-17
    • 1970-01-01
    • 2014-01-08
    • 2012-11-15
    相关资源
    最近更新 更多