admin管理员组文章数量:1185683
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';
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?
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';
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?
Share Improve this question asked Dec 30, 2012 at 1:22 ZeriumZerium 17.3k32 gold badges118 silver badges186 bronze badges2 Answers
Reset to default 18Get the img.width
and img.height
, then calculate the proportional height according to what width you're sizing to.
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.
Near the bottom of the page is the "ScaleImage" function. 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.
本文标签: javascriptHow to proportionally resize an image in canvasStack Overflow
版权声明:本文标题:javascript - How to proportionally resize an image in canvas? - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1738324377a2074652.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论