1

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();
flawr
  • 10,814
  • 3
  • 41
  • 71
  • 1
    can you provide a jsfiddle? – jCuga Oct 23 '14 at 20:16
  • I don't think he can provide jsfiddle because of security error – Gurkan İlleez Oct 23 '14 at 20:20
  • http://blog.sajithmr.me/javascript-check-an-image-is-loaded-or-not – Nick Maroulis Oct 23 '14 at 20:21
  • @jCuga here you go http://jsfiddle.net/flawr/4gqauLtv/ Currently the while loop is commented, so the canvas will be converted to grayscale before the image is even loaded. – flawr Oct 23 '14 at 20:23
  • This looks like the same security issue as found in: [context.getImageData() operation is insecure][1] [1]: http://stackoverflow.com/questions/17035106/context-getimagedata-operation-is-insecure – jCuga Oct 23 '14 at 20:37
  • I never got this security error, but the main question remains, how should can you make the program proceed only if the image is loaded? Is there a way of doing so without `onload`? – flawr Oct 23 '14 at 20:44

1 Answers1

0

I think your problem is that you are creating an image node but you never append the image to the DOM. Therefore the onload function will never be called.

  • The onload is being called and the image will be loaded just as it is now. So this is not a problem. – flawr Oct 23 '14 at 20:42