Firefox画布上传bug

时间:2016-08-16 16:05:10

标签: javascript canvas html5-canvas crop

我遇到了一个相当恼人的错误,同时调整http://croppic.net/裁剪图像的方式 - 而不是在服务器端裁剪它们,我在前端做它(使它们更快,它们的尺寸停止变成一个问题)。

问题是我的方法在Chrome和IE中运行得非常好,但没有别的; Firefox和Safari都支持Filereader API(我已经检查过了)。要使裁剪器工作,用户必须两次上传相同的图像 - 第一次将它留空,第二次将完美地工作。

为不整洁的代码道歉,在过去的几个小时里一直在黑客攻击和削减它。

守则是:

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");

1 个答案:

答案 0 :(得分:0)

Roland 是对的,我需要使用 onload 回调,但是在最后一张图片上。 我还设置了一个超时方法,完全等待图像加载:

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();
 }

}