我有这个使用回调的代码:
photoUploadLoad(e.target.result, ".upload-photos-container", function(resizedImg){});
我想在函数之外使用resizedImg
,如下所示:
$(emptyPhotos()[0]).attr('src', resizedImg);
这是photoUploadLoad函数:
function photoUploadLoad(imgUpload, element, callback) {
var img = new Image();
img.src = imgUpload;
img.onload = function() {
$(element).removeClass("loading");
var canvas=document.createElement("canvas");
var ctx=canvas.getContext("2d");
var iw=img.width;
var ih=img.height;
var scale=Math.min((maxW/iw),(maxH/ih));
var iwScaled=iw*scale;
var ihScaled=ih*scale;
canvas.width=iwScaled;
canvas.height=ihScaled;
ctx.drawImage(img,0,0,iwScaled,ihScaled);
img.src=canvas.toDataURL();
callback(img.src);
};
}
但一直未定义。有什么想法吗?
答案 0 :(得分:2)
onload
异步
您需要在callback
传入的匿名函数中执行此操作。
photoUploadLoad(e.target.result, ".upload-photos-container", function(resizedImg){
$(emptyPhotos()[0]).attr('src', resizedImg);
});