使用画布调整图像大小而不失真

Resize Image without Distortion using Canvas

本文关键字:图像 失真 调整 布调整      更新时间:2023-09-26

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

网页代码..

 <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小提琴的链接...

JS小提琴

像下面这样更改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();
}

更新的小提琴