Search code examples
javascriptjqueryhtmlcanvasjcrop

get original image size to crop and preview with canvas IE


Well, i made this question to show me some directions on working with crop and canvas.

everything works fine in that time, because i was not supose to give support to internet explorer, but, now on, its should be supported.

so, i dont know why, but seems to me that the problem its because IE its not getting the original image size.

everything work's fine in chrome, ff, opera, safari. IE its the only one showing some problems, the crop canvas result its not equal to the cropped area from image.

here is the main code to draw the cropped image

$("#crop").on("click", function(){
    var canvas = document.getElementById("canvasThumbResult");
    var context = canvas.getContext("2d");
    var img = document.getElementById("canvasToThumb"),
        $img = $(img),
        imgW = img.width, // chrome, ff... show as 1498, ie not
        imgH = img.height; // chrome, ff... show as 855, ie not

    var ratioY = imgH / $img.height(),
        ratioX = imgW / $img.width();

    var getX = $('#x').val() * ratioX,
        getY = $('#y').val() * ratioY,
        getWidth = $('#w').val() * ratioX,
        getHeight = $('#h').val() * ratioY;

    context.drawImage(img,getX,getY,getWidth,getHeight,0,0,320,320);
});

to see the problem, just run this on ie:

jsfiddle


Solution

  • Try using naturalWidth/naturalHeight instead width/height.

        var img = document.getElementById("canvasToThumb"),
        $img = $(img),
        imgW = img.naturalWidth,
        imgH = img.naturalHeight;
    

    jsfiddle