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