在图像加载之前不要解决承诺

时间:2015-03-06 23:46:47

标签: javascript jquery image base64

以下假设:

  • 循环播放一组img代码
  • 抓住每个代码的src网址
  • 使用base64 HTML 5
  • 将其转换为canvas个编码字符串
  • 一旦转换了所有图像,就应该解决承诺,并且回调称为

我的问题:

  • 我需要等待每个图片加载canvas才能将其转换为base64
  • 解决这个问题我使用`img.onload = function(){..... return base64Img; };
  • 不幸的是,每次通过解析承诺调用img.src = element.src;,它都不会等待图片加载并调用return base64Img;所以当$.when.apply($, promises).then(function(){}); function accountCreation(){ $('#container').hide(); // hide the display while we save the info as it will take a few seconds, you should do a loading bar or something here instead var user = Parse.User.current(); // get the currently logged in user object // loop through each image element var promises = $('.images').map(function(index, element) { var src = $(element).attr('src'); var canvas = document.createElement('CANVAS'); var ctx = canvas.getContext('2d'); var img = new Image; img.crossOrigin = 'Anonymous'; img.onload = function(){ canvas.height = img.height; canvas.width = img.width; ctx.drawImage(img,0,0); var base64Img = canvas.toDataURL('image/png'); // Clean up canvas = null; return base64Img; }; img.src = element.src; }); $.when.apply($, promises).then(function() { // arguments[0][0] is first result // arguments[1][0] is second result and so on for (var i = 0; i < arguments.length; i++) { var file = new Parse.File("photo.jpg", { base64: arguments[i]}); // this part actually saves the image file to parse user.set("image" + i, file); // set this image to the corosponding column on our object } // save the user object user.save(null,{ success: function(user) { $('#message').html('Profile Updated!'); $('#container').show(); // show the screen again, you should just remove your loading bar now if you used one }, error: function(user, error) { console.log('Failed to create new object, with error code: ' + error.message); } }); }); } 时,我最终得到一个空数组调用。

如何更改此承诺,以便在所有图片都已加载并转换后才能解决?

{{1}}

1 个答案:

答案 0 :(得分:1)

您的promise数组只包含未定义的值,因为回调函数不返回任何内容。由于数组中没有Deferred个对象,when方法没有等待的任何内容,因此它会立即运行then回调。

创建要返回的Deferred对象,并在加载图像时解析它:

var promises = $('.images').map(function(index, element) {
    // created a Deferred object to return
    var deferred = $.Deferred();
    var src = $(element).attr('src');
    var canvas = document.createElement('CANVAS');
    var ctx = canvas.getContext('2d');
    var img = new Image;
    img.crossOrigin = 'Anonymous';
    img.onload = function(){
        canvas.height = img.height;
        canvas.width = img.width;
        ctx.drawImage(img,0,0);
        var base64Img = canvas.toDataURL('image/png');
        // Clean up
        canvas = null;
        // Resolve the Deferred object when image is ready
        deferred.resolve(base64Img);
    };
    img.src = element.src;
    // return the Deferred object so that it ends up in the array
    return deferred;
});