简体   繁体   English

如何在画布中按比例调整图像大小?

[英]How to proportionally resize an image in canvas?

AFAIK, to resize a loaded image in HTML5 canvas would be done like this: AFAIK,在HTML5画布中调整加载图像的大小将如下所示:

var img = new Image();
img.onload = function () {
  ctx.drawImage(img, 0, 0, 300, 200); // resizes image to 300px wide, 200px high
}
img.src = 'images/myimage.jpg';

But then I realised that the image wouldn't be proportionally correct. 但后来我意识到图像不会按比例正确。 So then I tried using one parameter only (just like in HTML) but I found that didn't work either. 那么我只尝试使用一个参数(就像在HTML中一样),但我发现它也没有用。

How do I proportionally resize the image? 如何按比例调整图像大小?

Get the img.width and img.height , then calculate the proportional height according to what width you're sizing to. 获取img.widthimg.height ,然后根据您要调整的宽度计算比例高度。

For example : 例如

ctx.drawImage(img, 300, 0, 300, img.height * (300/img.width));

I wrote a blog article on this topic last last year. 去年我写了一篇关于这个主题的博客文章。 You can read it here . 你可以在这里阅读。 Basically it provides a function for scaling an image with a proper aspect ratio. 基本上它提供了用适当的宽高比缩放图像的功能。 It includes supporting both landscape and portrait orientations and sizing between the two. 它包括支持横向和纵向方向以及两者之间的尺寸。 You can even choose between "letterbox" and "pan and scan (zoom)" mode. 您甚至可以在“信箱”和“平移和扫描(缩放)”模式之间进行选择。

It was written with div positioning in mind, but could be easily be understood for canvas. 它是以div定位编写的,但可以很容易地被理解为画布。

Near the bottom of the page is the "ScaleImage" function. 页面底部附近是“ScaleImage”功能。 That might be what you want. 那可能就是你想要的。 Then you can apply it as follows: 然后您可以按如下方式应用它:

var img = new Image();
img.onload = function () {

  var result = ScaleImage(img.width, img.height, 300, 200, true);

  ctx.drawImage(img, result.targetleft, result.targettop, result.width, result.height); // resizes image to a target size of 300x200 using letterbox mode
}
img.src = 'images/myimage.jpg';

You can replace result.targetleft and result.targettop with "0" if you don't want the image centered. 如果您不希望图像居中,可以将result.targetleft和result.targettop替换为“0”。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM