drawImage将图像调整为500px高

时间:2017-09-20 14:47:54

标签: javascript html css drawimage

我正在尝试拍摄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>
&#13;
&#13;
&#13;

如何指定生成的图像尺寸,使宽度自动?我最终希望此功能将任何图像的大小调整为500像素高。

2 个答案:

答案 0 :(得分:1)

我将比率应用于你对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>

答案 1 :(得分:1)

这是一个解决方案,有点迂回,但似乎有效。我使用原始大小的画布中的toDataURL()创建了一个新图像。尽管新图像被缩小,但是总尺寸仍然是原始图像的尺寸,使得剩余空间是透明的。然后我将此图像设置并剪辑到新画布中。生成的画布具有正确大小的图像,可以使用所需尺寸进行复制和粘贴。

如果下面的代码段没有在新画布中显示图片,请尝试使用以下小提琴: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>