I have following code where I load an image and write it on canvas. After the image is loaded I want to further edit the canvas but the image must be loaded at this moment. Currently I tried to prevent the constructor of the class to finish untill the image is loaded, but this does not seem to work, because it keeps 'waiting' even when the image is already there.
Can you tell my why this does not work?
And I can see that this is not a good solution, can you tell me how it should be done?
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();