为什么我的javascript Promise卡在“待定”状态?

时间:2015-12-17 14:11:38

标签: javascript canvas promise

我有一个绘制到画布的复杂SVG,这个任务需要在绘制其他对象之前完成。这是一个模拟这个的小提琴:

https://jsfiddle.net/1hucuLg9/1/

React.cloneElement(this.props.children, {title: this.state.title, status: this.state.status})

你会在小提琴中注意到只绘制了SVG,而不是之后的其他图像。用于绘制SVG的//draw svg var promise = new Promise(function(){ drawSwatch(document.getElementById("mySwatch")); //not typo, canvas context is referenced inside this function due to xml complexity in this fiddle }); //draw image promise.then(function(){ ctx.drawImage(document.getElementById("myImg",0,0,150,150)); }); 被卡住等待...即使内部javascript全部被执行。发生了什么事?

2 个答案:

答案 0 :(得分:2)

您应解决承诺。承诺docs应该是有用的。

var promise = new Promise(function(resolve, reject){
  drawSwatch(document.getElementById("mySwatch"));
  resolve();
});
promise.then(function(){
  ctx.drawImage(document.getElementById("myImg",0,0,150,150));
});

答案 1 :(得分:0)

如果您只想在myImg内的图片加载后添加drawSwatch,则可以执行此操作

var canvas = document.getElementById("myCanvas");
var ctx = canvas.getContext("2d");

//hard code variables for example
var vw=300, vh=200, x=20, y=50, w=250, h=50; rx=10, ry=5, bg="#fae", theta=15, midptX=100, midptY=120, blur=5;

//helper function to draw swatch objects
function drawSwatch(currentSwatch, resolve){ // extra parameter
    var data = '<svg xmlns="http://www.w3.org/2000/svg" width="'+vw+'" height="'+vh+'">'+
    '<defs>'+
    '<filter id="f1">'+
    '<feGaussianBlur in="SourceGraphic" stdDeviation="'+blur+'" />'+
    '</filter>'+
    '</defs>'+
    '<rect class="shape" x="0" y="0" width="'+w+'" height="'+h+'" rx="'+rx+'" ry="'+ry+'" transform="translate('+x+','+y+') rotate('+theta+','+midptX+','+midptY+')" fill="'+bg+'" filter="url(#f1)"></rect>'+
    '</svg>';

    //now draw the svg to canvas
    var svg_data = encodeURIComponent(data);
    // create a dataURI version
    var url = 'data:image/svg+xml; charset=utf8, ' + svg_data;
    var img = new Image();
    img.onload = function(){
      ctx.drawImage(img, 0, 0, vw, vh);
      resolve(); // call the passed in resolve function
    }
    img.src = url;
}

//draw svg
var promise = new Promise(function(resolve){ 
  drawSwatch(document.getElementById("mySwatch"), resolve); // call drawSwatch passing in the resolve function
});

promise.then(function(){
  ctx.drawImage(document.getElementById("myImg"),0,0,150,150);
});

drawSwatch添加了第二个参数,这是promise构造函数的resolve函数

现在,在img.onload被解雇之前,不会调用promise.then中的回调

working fiddle - 在小提琴中,我没有直接调用resolve,而是将它放在setTimout中,以表明在实际解析promise之前不会执行.then