如何在canvas中按比例调整图像大小? [英] How to proportionally resize an image in canvas?
本文介绍了如何在canvas中按比例调整图像大小?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
AFAIK,要调整HTML5 canvas中加载的图片的大小,可以这样做:
AFAIK, to resize a loaded image in HTML5 canvas would be done like this:
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';
但我意识到图像不会成比例地正确。所以我试着只使用一个参数(就像在HTML中),但我发现,也没有工作。
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.
如何按比例调整图像大小? >
How do I proportionally resize the image?
推荐答案
获取 img.width
和 img.height
,然后根据您要调整的宽度计算比例高度。
Get the img.width
and img.height
, then calculate the proportional height according to what width you're sizing to.
ctx.drawImage(img, 300, 0, 300, img.height * (300/img.width));
这篇关于如何在canvas中按比例调整图像大小?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文