Resizing photo on a canvas without losing the aspect ratio

前端 未结 2 1991
难免孤独
难免孤独 2021-01-18 09:19

Hi all thanks for any help in advance. I am writing a phonegap app and can not get the photo to shrink without either losing the aspect or cropping the image by mistake. I

2条回答
  •  旧时难觅i
    2021-01-18 09:59

    Scaling is built in to drawImage.

    Don't use setAttribute when dealing with canvas, call canvas.width = 272 instead, and only with whole pixel values.

    Here is some working code to get you started:

     function onPhotoDataSuccess(imageData)
    {
    var myImage = new Image();
    var thecanvas = document.getElementById("queImg");
    var ctx = thecanvas.getContext("2d");
    
        myImage.onload = function() {
        ctx.drawImage(myImage, 0, 0, myImage.width * 0.15, myImage.height * 0.15);
        }     
    
        myImage.src = "http://placekitten.com/1296/968";
    }
    
    
    onPhotoDataSuccess(null);
    

    Live example:

    http://jsfiddle.net/QBTrg/6/

提交回复
热议问题