Resizing photo on a canvas without losing the aspect ratio

前端 未结 2 1973
难免孤独
难免孤独 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条回答
  • 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/

    0 讨论(0)
  • 2021-01-18 10:01

    You can just draw like this, without the scale function:

    ctx.drawImage(myImage, 0, 0, myImage.width * 0.15, myImage.height * 0.15);
    

    However, the resolution has to be set explicitly, not in terms of percentages. E.g.:

    window.onload = function() {
        thecanvas.width = window.width;
        thecanvas.height = window.height;
    }
    
    0 讨论(0)
提交回复
热议问题