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

Javascript drawImage-调整大小并保持比例,javascript,html,css,drawimage,Javascript,Html,Css,Drawimage,我正在尝试使用drawImage调整图像大小,但保持比例不变。到目前为止我有这个 window.onload=function(){ var c=document.getElementById(“myCanvas”); var ctx=c.getContext(“2d”); var img=document.getElementById(“尖叫”); ctx.drawImage(img,0,0,600,428); } 要使用的图像: 画布: 您的浏览器不支持HTML5画布标记。 首先,您需要找

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

window.onload=function(){
var c=document.getElementById(“myCanvas”);
var ctx=c.getContext(“2d”);
var img=document.getElementById(“尖叫”);
ctx.drawImage(img,0,0,600,428);
}
要使用的图像:

画布:

您的浏览器不支持HTML5画布标记。
首先,您需要找到图像和画布的纵横比。这是通过以下方式实现的:

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

要适合图像,请使用
Math.min

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

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

要适合图像,请使用
Math.min

您的意思是保持比例?你是说保持这个比例?比如说,是在一个项目中还是在一个项目中?