简体   繁体   中英

Firefox canvas upload bug

I've encountered a rather annoying bug, whilst adjusting http://croppic.net/ way of cropping images - rather than cropping them on the server side, I do it on the front end (renders them faster and their sizes stop becoming an issue).

The problem is that my method works perfectly fine in Chrome and IE, but nothing else; both Firefox and Safari support Filereader API (I've already checked that). For cropper to work, users have to upload the same image twice - where the first time it will be blank, and the second time it will work perfectly.

Apologies for not tidy code, been hacking and slashing it for the last couple of hours.

The Code is:

var crop_canvas,
left = Math.abs( parseInt( that.img.css('left') ) ), 
top =  Math.abs( parseInt( that.img.css('top') ) ),
width = that.imgInitW;
height = that.imgInitH;    
crop_canvas = document.createElement('canvas');

var secondW = that.imgW;
var secondH = that.imgH;

crop_canvas.width = secondW;
crop_canvas.height = secondH;

image_target = new Image();
image_target.src = that.imgUrl;
var newImg = new Image();  
crop_canvas.getContext('2d').drawImage(image_target, 0, 0, secondW, secondH);
newImg.src = crop_canvas.toDataURL("image/png");
//starts breaking here
var finalImg = new Image();
var new_canvas = document.createElement('canvas');
new_canvas.width = that.objW;
new_canvas.height = that.objH;
var img_last = new_canvas.getContext('2d').drawImage(newImg, left, top,  that.objW, that.objH, 0, 0,that.objW, that.objH);
finalImg.src = img_last.toDataURL("image/png");

Roland was right, I needed to use an onload callback, but on the last image. I also set a timeout method, that fully waits for the image to load:

var finalImg = new Image();
finalImg.onload = setTimeout(makingImg, 2000);

function makingImg(){
   new_canvas.getContext('2d').drawImage(newImg, left, top, that.objW, that.objH, 0, 0,that.objW, that.objH);
   finalImg.src = new_canvas.toDataURL("image/png");
   if (that.options.imgEyecandy)
   that.imgEyecandy.hide();

   that.destroy();

   that.obj.append('<img class="croppedImg" src="' + finalImg.src + '">');

                 if (that.options.outputUrlId !== '') { $('#' + that.options.outputUrlId).val(response.url); }

                 that.croppedImg = that.obj.find('.croppedImg');

                 that.init();

                 that.hideLoader();
                 that.afterCrop();
 }

}

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