加载页面时,文件读取器会循环加载图像文件。文件读取器仅读取最后一张图像。我试图在File Reader上使用IIFE构造函数。但没有任何效果。
代码
function getDataUri(url,cb){
var image = new Image();
image.onload = function() {
var canvas = document.createElement('canvas');
canvas.width = this.naturalWidth;
canvas.height = this.naturalHeight;
canvas.getContext('2d').drawImage(this, 0, 0);
cb(canvas.toDataURL('image/jpeg'));
};
image.setAttribute('crossOrigin', 'anonymous');
image.src = url;
}
// Dropzone method
$scope.photoMethods = {};
// Let's said photosURIs had 3 elements
photosURIs.forEach(function(imageURI){
getDataUri(imageURI, function(dataUri){
var blob = util.dataURItoBlob(dataUri);
// Dropzone
blob['status'] = 'queued';
$scope.photoMethods.emit("addedfile", blob); // emit addedFile function
$scope.photoMethods.files.push(blob);
})
})
// Dropzone callback
$scope.dzPhotoCallbacks = {
'addedfile' : function(origFile){
// Execute 3 times at this line
$rootScope.addWatermark(origFile, function(watermarkImage, width, height){
// Execute here only once.
});
}
}
$rootScope.addWatermark = function(origFile, cb){
// IIFE return callback function only once.
(function(origFile, cb){
let reader = new FileReader();
reader.addEventListener("load", function(ev) {
let origImg = new Image();
origImg.src = ev.target.result;
origImg.addEventListener("load", function(event){
let width = event.target.width;
let height = event.target.height;
$rootScope.applyImageWatermark(origImg, event.target.width, event.target.height, function(canvas){
cb(canvas, width, height); // run once
});
})
origImg.addEventListener("error", function(error){
console.log('error: ' + JSON.stringify(error))
})
});
reader.readAsDataURL(origFile);
})(origFile, cb);
}
上面的代码从Array读取图像URI,并将其转换为Blob文件,然后将其添加到Dropzone,然后在文件阅读器上为图像blob加上水印。
我的问题是文件读取器仅读取最后一个文件一次,而没有回调3次。