简体   繁体   中英

jQuery deferred not working on chrome and safari?

I want drawImage on canvas tag and then save it again. And I use deferred.done() of jQuery.

Here is the code I use :

function save_submit() {
    LoadDraw().done(function(){
      var canvas = document.getElementById('touchpaint');
      var ctx = canvas.getContext('2d');
      var image = canvas.toDataURL();
    });
var LoadDraw = function () {
    var r = $.Deferred();
    var canvas = document.getElementById('touchpaint');
    var ctx = canvas.getContext('2d');
    var imageLoader = 'http://img262.imageshack.us/img262/3453/gokum.jpg';
    var img = new Image();
    $(img).load(function (){
      ctx.globalCompositeOperation = "destination-over";
      ctx.drawImage(img,0,0);
    });
    img.crossOrigin = '';
    img.src = imageLoader;    
    r.resolve();
    return r;
  }

It works fine on Firefox. But does not work on Chrome and Safari. I am looking for help. Thank you.

Well, you are not using the Deferred correctly. The idea of a Deferred object is to resolve it in some kind of callback function, not 'directly' after you create it.

In your case, you probably should resolve the deferred (r) in the $(img).load callback function:

var LoadDraw = function () {
    var r = $.Deferred();
    var canvas = document.getElementById('touchpaint');
    var ctx = canvas.getContext('2d');
    var imageLoader = 'http://img262.imageshack.us/img262/3453/gokum.jpg';
    var img = new Image();
    $(img).load(function (){
      ctx.globalCompositeOperation = "destination-over";
      ctx.drawImage(img,0,0);
      r.resolve();
    });
    img.crossOrigin = '';
    img.src = imageLoader;    

    return r;
  }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM