drawImage 将图像调整为 500px 高

drawImage resize image to 500px high

我正在尝试拍摄 1280x960 的图像并使用 drawImage 调整其大小,使其高 600 像素。我已经计算出我认为我需要实现这一目标的比率,但不知道如何应用...

var canvas = document.getElementById('mycanvas');
var ctx = canvas.getContext('2d');
var img = new Image();
img.onload = function () {
  canvas.height = this.height;
  canvas.width = this.width;
  
  ratio = canvas.height / canvas.width;
  
  console.log(canvas.width + 'x' + canvas.height + ' | ratio = ' + ratio);
  
  ctx.drawImage(img, 0, 0, 300, 500);
}
img.src = 'https://c.slashgear.com/wp-content/uploads/2015/06/dxo-one-sample-3-1280x960.jpg';
<canvas id="mycanvas"></canvas>

如何指定生成的图像大小,使宽度自动设置?我最终希望这个函数可以将任何图像的大小调整为 500 像素高。

我将该比率应用到您对 drawImage 的调用中,它似乎有效:

ctx.drawImage(img, 0, 0, 500 / ratio, 500);

var canvas = document.getElementById('mycanvas');
var ctx = canvas.getContext('2d');
var img = new Image();
img.onload = function () {
  canvas.height = this.height;
  canvas.width = this.width;
  
  ratio = canvas.height / canvas.width;
  
  console.log(canvas.width + 'x' + canvas.height + ' | ratio = ' + ratio);
  
  ctx.drawImage(img, 0, 0);
  canvas.style.width = 500 / ratio + "px";
  canvas.style.height = 500 + "px";
}
img.src = 'https://c.slashgear.com/wp-content/uploads/2015/06/dxo-one-sample-3-1280x960.jpg';
<canvas id="mycanvas"></canvas>

这是一个解决方案,有点迂回但似乎可行。我使用 toDataURL() 从原始尺寸 canvas 创建了一个新图像。新图虽然缩小了,但总维度还是原图的维度,所以剩下的space是透明的。然后我将这张图片设置并剪辑成一个新的 canvas。生成的 canvas 具有正确大小的图像,可以按所需尺寸复制和粘贴。

如果下面的代码片段没有在新的 canvas 中显示图像,请尝试以下 fiddle,它似乎运行良好:https://jsfiddle.net/jfeferman/u80fhy0z/

var canvas = document.getElementById('mycanvas');
var ctx = canvas.getContext('2d');
var img = new Image();
img.crossOrigin = "Anonymous";
img.onload = function () {
  canvas.height = this.height;
  canvas.width = this.width;
  
  ratio = canvas.height / canvas.width;
  
  console.log(canvas.width + 'x' + canvas.height + ' | ratio = ' + ratio);
  
  ctx.drawImage(img, 0, 0, 500 / ratio, 500);
  
  var newImage = new Image();
  newImage.crossOrigin = "Anonymous";
  newImage.src = canvas.toDataURL();
  
  var newCanvas = document.getElementById("newcanvas");
  newCanvas.height = 500;
  newCanvas.width = 500 / ratio;
  var newCtx = newCanvas.getContext('2d');
  newCtx.drawImage(newImage, 0, 0, 500 / ratio, 500, 0, 0, 500 / ratio, 500);
}
img.src = 'https://c.slashgear.com/wp-content/uploads/2015/06/dxo-one-sample-3-1280x960.jpg';
#mycanvas {
  display: none;
}
<canvas id="newcanvas"></canvas>
<canvas id="mycanvas"></canvas>