等到图像加载后再继续

时间:2014-10-23 20:13:08

标签: javascript

我有以下代码,我在其中加载图像并将其写在画布上。加载图像后,我想进一步编辑画布,但此时必须加载图像。目前我试图阻止类的构造函数完成,直到图像被加载,但这似乎不起作用,因为它保持等待'即使图像已经存在。

你能告诉我为什么这不起作用吗?

我可以看到这不是一个好的解决方案,你能告诉我应该怎么做吗?

var Handler = function(canvasId,imageSrc){

  this.canvas = document.getElementById(canvasId);
  this.ctx = this.canvas.getContext("2d");
  var self = this;
  var image = new Image();
  image.src = imageSrc;
  this.finish = false;
  image.onload = function(){
    self.canvas.width = this.width;
    self.canvas.height = this.height;
    self.ctx.drawImage(image,0,0, self.canvas.width,self.canvas.height,
                        0,0,this.width,this.height); 
    self.finish = true;
  };

  this.applyFilter = function(filter){
        //some unimportant code code....
  };

  this.toGrayScale = function(){
    var imgData = this.ctx.getImageData(0,0,this.canvas.width,this.canvas.height);
        ///manipulate the data ....
    this.ctx.putImageData(imgData,50,50);

  };

  while(!this.finish){};

};//end handler

 var handler = new Handler("myCanvas","myImage.jpg");
 handler.applyFilter(1); //will be executed before image has loaded if you remove while loop
 handler.toGrayScale();

1 个答案:

答案 0 :(得分:0)

我认为你的问题是你正在创建一个图像节点,但你永远不会将图像附加到DOM。因此永远不会调用onload函数。