【问题标题】:Firefox canvas upload bugFirefox 画布上传错误
【发布时间】:2016-08-16 16:05:09
【问题描述】:

我在调整http://croppic.net/ 裁剪图像的方式时遇到了一个相当烦人的错误 - 我不是在服务器端裁剪它们,而是在前端进行(渲染速度更快,它们的大小不再成为问题) .

问题是我的方法在 Chrome 和 IE 中运行良好,但没有别的; Firefox 和 Safari 都支持 Filereader API(我已经检查过了)。为了让cropper正常工作,用户必须上传同一张图片两次——第一次是空白的,第二次可以正常工作。

抱歉,代码不整洁,在过去的几个小时里一直在修改和削减代码。

代码是:

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

【问题讨论】:

  • 你需要等待图片加载(image_target.onload = doMagic)
  • 尝试这样做,然后也尝试在第二张图像上这样做。效果一样,但可以再试一次。我什至使用window.open(image.src, "_blank") 来查看哪些图像加载正确
  • 您在加载之前绘制图像。在新的水龙头中打开它以查看图像是否存在在这里没有帮助。
  • that.imgURL 是一个已经编码为 Base64 的参数,所以我实际上只是在 onload 中添加了一个警报,但仍然是同样的问题。
  • 嗯,你能用加载的东西更新代码吗?

标签: javascript canvas html5-canvas crop


【解决方案1】:

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

}

【讨论】:

    猜你喜欢
    • 2014-01-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-05-17
    • 2015-09-15
    • 2013-07-11
    • 1970-01-01
    • 2015-08-01
    相关资源
    最近更新 更多