Javascript 如何在画布中按比例调整图像大小?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/14087483/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to proportionally resize an image in canvas?
提问by Lucas
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?
如何按比例调整图像大小?
回答by robertc
Get the img.widthand img.height, then calculate the proportional height according to what width you're sizing to.
获取img.widthand img.height,然后根据您调整大小的宽度计算比例高度。
例如:
ctx.drawImage(img, 300, 0, 300, img.height * (300/img.width));
回答by selbie
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 定位的情况下编写的,但对于 canvas 来说很容易理解。
Near the bottom of the page is the "ScaleImage" function. That might be what you want. Then you can apply it as follows:
靠近页面底部的是“ScaleImage”功能。那可能就是你想要的。然后您可以按如下方式应用它:
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”。

