Canvas drawImage缩放

sel*_*c82 53 javascript resize canvas drawimage html5-canvas

我正在尝试按比例缩放图像到画布.我可以用固定的宽度和高度来缩放它,如下所示:

context.drawImage(imageObj, 0, 0, 100, 100)
Run Code Online (Sandbox Code Playgroud)

但我只想调整宽度并按比例调整高度.类似于以下内容:

context.drawImage(imageObj, 0, 0, 100, auto)
Run Code Online (Sandbox Code Playgroud)

我看到了我能想到的所有地方,并没有看到这是否可能.

Gau*_*rav 90

context.drawImage(imageObj, 0, 0, 100, 100 * imageObj.height / imageObj.width)
Run Code Online (Sandbox Code Playgroud)


小智 5

@TechMaze的解决方案是相当不错的。

这是经过一些正确性和介绍image.onload事件后的代码。为了避免任何形式的扭曲,image.onload至关重要。

function draw_canvas_image() {

var canvas = document.getElementById("image-holder-canvas");
var context = canvas.getContext("2d");
var imageObj = document.getElementById("myImageToDisplayOnCanvas");

imageObj.onload = function() {
  var imgWidth = imageObj.naturalWidth;
  var screenWidth  = canvas.width;
  var scaleX = 1;
  if (imgWidth > screenWidth)
      scaleX = screenWidth/imgWidth;
  var imgHeight = imageObj.naturalHeight;
  var screenHeight = canvas.height;
  var scaleY = 1;
  if (imgHeight > screenHeight)
      scaleY = screenHeight/imgHeight;
  var scale = scaleY;
  if(scaleX < scaleY)
      scale = scaleX;
  if(scale < 1){
      imgHeight = imgHeight*scale;
      imgWidth = imgWidth*scale;          
  }

  canvas.height = imgHeight;
  canvas.width = imgWidth;

  context.drawImage(imageObj, 0, 0, imageObj.naturalWidth, imageObj.naturalHeight, 0,0, imgWidth, imgHeight);
}
}
Run Code Online (Sandbox Code Playgroud)