简体   繁体   中英

Javascript: Setting Image to Canvas doesn't work right

I'm basically trying to get the selected image file from a input dialog and set it to a canvas that's in my HTML. However, the image gets cropped and only a portion of the image is shown .

Javascript :

function onSS1Change(file) {
    var ctx = document.getElementById('canvas').getContext('2d');
    var img = new Image;
    img.onload = function () {
        ctx.drawImage(img, 20, 20);
    }
    img.src = URL.createObjectURL(file.target.files[0]);
}

HTML :

<input id="ss1-inputdiag" type="file" onchange="onSS1Change(event)" />

Fiddle : http://jsfiddle.net/tdy9tqfh/

I need to get the original height and width

What am I doing wrong?

jsFiddle : http://jsfiddle.net/CanvasCode/tdy9tqfh/2/

Just update the canvas height and width to fit the image, also you were drawing your image at position x 20 and y 20 so all your images will be slightly cut off at the right side and bottom.

var input = document.getElementById('input'); input.addEventListener('change', handleFiles);

function handleFiles(e) {
    var c = document.getElementById('canvas');
    var ctx = c.getContext('2d');

    var img = new Image;
    img.src = URL.createObjectURL(e.target.files[0]);
    img.onload = function() {
        c.width = img.width;
        c.height = img.height;
        ctx.drawImage(img, 0,0);
        alert('the image is drawn');
    }
}

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