views:

17

answers:

2

What would be the best way to call render() once all the imageData vars have been populated?

would I just call them all in sequence using callbacks, and call render, or is there a better method?

function loadImageData()
    {

        //Get Background Image Data
        var backgroundImg = loadImage(background, function(){
            backgroundData = getDataFromImage(backgroundImg);
        }); 

        //Get Overlay Image Data
        var overlayImg = loadImage(overlay, function(){
            overlayData = getDataFromImage(overlayImg);

        }); 

        //Get more Image Data
        //Get more Image Data
        //Get more Image Data

    }

    function render()
    {
        ctx.putImageData(backgroundData, 0,0);
    }
+1  A: 

From inside the callbacks, "render" the individual image elements onto the canvas.

    var backgroundImg = loadImage(background, function(){
        backgroundData = getDataFromImage(backgroundImg);
        ctx.putImageData(backgroundData, 0,0);
    }); 
CD Sanchez
yes this renders the images to the canvas fine, but I don't need to at this stage - just make sure all the data is loaded before trying to call the next part of the program.
davivid
A: 

My approach would include creating a "counter" of the number of callbacks you need, something like this:

function loadImageData()
{
  var counter = 5;
  function imageReceived() {
    if (--counter == 0) render();
  }
  //Get Background Image Data
  var backgroundImg = loadImage(background, function(){
    backgroundData = getDataFromImage(backgroundImg);
    imageReceived();
  }); 

  //Get Overlay Image Data
  var overlayImg = loadImage(overlay, function(){
    overlayData = getDataFromImage(overlayImg);
    imageReceived();
  }); 

    //Get more Image Data
    //Get more Image Data
    //Get more Image Data

Of course, I would probably rewrite it in such a way that the number of waiting requests was increased in the loadImage() function, and have a global callback that gets fired whenever the number of requests waiting gets back to 0.

gnarf
cool this was what I had played around with earlier and managed to get working, didnt know if it was a good way or not though! thanks.
davivid