How to proportionally resize an image in canvas?

后端 未结 2 2183
猫巷女王i
猫巷女王i 2020-12-16 20:41

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, 20         


        
2条回答
  •  一个人的身影
    2020-12-16 21:29

    Get 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));
    

提交回复
热议问题