简体   繁体   中英

HTML5 Image fit Issue in Canvas

I am working on HTML5 application for mobile. I am using a canvas element and file upload element. Whenever user hit this file upload element from mobile. He sees two options. 1. Choose existing photo 2. Take new photo

If he choose existing photo, this is fixed well in my canvas but if he clicks new photo, it does not fit into canvas. Width is fine but height of click image shown in canvas in not more than 50px.

My HTML code:

<canvas id="myCanvas" width="270" height="300"></canvas>
<input type="file" id="uploadImage" name="upload" value="Upload" onchange="PreviewImage();" />

My Javascript Code

function PreviewImage() {
    var oFReader = new FileReader();
    oFReader.readAsDataURL(document.getElementById("uploadImage").files[0]);
    oFReader.onload = function (oFREvent) {
        var canvas = document.getElementById('myCanvas');
        ctx = canvas.getContext('2d');
        ctx.clearRect(0, 0, 270, 300);            
        imageUrl = oFREvent.target.result;
        var base_image = new Image();
        base_image.src = imageUrl;
        base_image.onload = function () {
        ctx.drawImage(base_image, 0, 0, 270, 300);
    }
    };
}

I have searched many sites but could not find solution of this issue. Any help?

The first thing I noticed in the PreviewImage function was where the image is being drawn to the canvas:

ctx.drawImage(base_image, 0, 0, 270, 300);

The last two attributes of CanvasRenderingContext2D.drawImage will resize the image, ignoring the aspect ratio, to 270 x 300. If you remove them the image will render at it's original size.

ctx.drawImage(base_image, 0, 0);

To fit the image within the width of the canvas use the following:

ctx.drawImage(base_image, 0, 0, canvas.width, base_image.height * (canvas.width / base_image.width));

As for the image rendering with a bizarre height (~50px) that could be an iOS specific issue related to images over 2MB getting subsampled. See HTML5 Canvas drawImage ratio bug iOS for more information.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM