开发者

call backs / que loading - call function after complete

开发者 https://www.devze.com 2023-01-15 08:24 出处:网络
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 callb开发者_运维问答acks, and call render, or is there a bett

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 callb开发者_运维问答acks, 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);
    }


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);
    }); 


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消