Scaling an image to fit on canvas

后端 未结 2 935
伪装坚强ぢ
伪装坚强ぢ 2020-12-07 11:03

I have a form that allows a user to upload an image.

Once the image is loaded, we perform some scaling on it in order to reduce its filesize before we pass it back t

2条回答
  •  死守一世寂寞
    2020-12-07 11:15

    You made the error, for the second call, to set the size of source to the size of the target.
    Anyway i bet that you want the same aspect ratio for the scaled image, so you need to compute it :

    var hRatio = canvas.width / img.width    ;
    var vRatio = canvas.height / img.height  ;
    var ratio  = Math.min ( hRatio, vRatio );
    ctx.drawImage(img, 0,0, img.width, img.height, 0,0,img.width*ratio, img.height*ratio);
    

    i also suppose you want to center the image, so the code would be :

    function drawImageScaled(img, ctx) {
       var canvas = ctx.canvas ;
       var hRatio = canvas.width  / img.width    ;
       var vRatio =  canvas.height / img.height  ;
       var ratio  = Math.min ( hRatio, vRatio );
       var centerShift_x = ( canvas.width - img.width*ratio ) / 2;
       var centerShift_y = ( canvas.height - img.height*ratio ) / 2;  
       ctx.clearRect(0,0,canvas.width, canvas.height);
       ctx.drawImage(img, 0,0, img.width, img.height,
                          centerShift_x,centerShift_y,img.width*ratio, img.height*ratio);  
    }
    

    you can see it in a jsbin here : http://jsbin.com/funewofu/1/edit?js,output

提交回复
热议问题