使用 Canvas 无失真调整图像大小

Resize Image without Distortion using Canvas

我正在尝试加载 canvas 中存储在本地计算机中的图像文件。我可以在 canvas 中加载图像,但如果图像的宽度或高度非常大,图像就会变形。我想使用 canvas 将图像的尺寸调整为 300 x 300,而不管图像的大小如何都不会扭曲图像。我尝试了很长时间,但无法弄清楚我哪里出错了。请帮忙..

HTML代码..

 <input type="file" id="ifile">
 <canvas id="panel"></canvas> 

JS代码..

 //beginning of image display
        canvasCtx = document.getElementById("panel").getContext("2d");

        document.getElementById("ifile").onchange = function(event) {

            this.imageFile = event.target.files[0];

            var reader = new FileReader();
            reader.onload =  function(event) {
                var img = new Image();
                //img.style.width = "300px";
                //img.style.height = "300px";

                img.onload = function() {
                    drawImage(img);
                }
                img.src = event.target.result;

            }
            reader.readAsDataURL(this.imageFile);
        }

        drawImage = function(img) {
            this.canvasCtx.canvas.width = 300;//img.width;
            this.canvasCtx.canvas.height = 300;//img.height;
            this.canvasCtx.drawImage(img,0,0,300,300);
            url = canvasCtx.canvas.toDataURL();
            console.log(url);
        }           
        //end of image display

JS Fiddle的link也在下面给出...

JS Fiddle

更改您的 drawImage 函数,如下所示。我在顶部声明了一个全局变量 canvas

drawImage = function(img) {
    // if else to keep aspect ratio in 300X300
    if(img.width>img.height){
        canvas.width = 300;
        canvas.height = 300 / img.width * img.height;
    } else {
        canvas.width = 300 / img.height * img.width;
        canvas.height = 300;
    }    

    this.canvasCtx.drawImage(img, 0, 0, canvas.width, canvas.height);
    url = canvasCtx.canvas.toDataURL();
}

UPDATED FIDDLE