Link to home
Start Free TrialLog in
Avatar of jagguy
jagguyFlag for Australia

asked on

load many images

In html5 canvas I can load 1 image. To load many images I look at this code
I am confused as to how this work with the callback

 loadImages(sources, function(images) {// where is function(images) to pass?

 <body>
    <canvas id="myCanvas" width="578" height="200"></canvas>
    <script>
      function loadImages(sources, callback) {
        var images = {};
        var loadedImages = 0;
        var numImages = 0;
        // get num of sources
        for(var src in sources) {
          numImages++;
        }
        for(var src in sources) {
          images[src] = new Image();
          images[src].onload = function() {
            if(++loadedImages >= numImages) {
              callback(images);
            }
          };
          images[src].src = sources[src];
        }
      }
      var canvas = document.getElementById('myCanvas');
      var context = canvas.getContext('2d');

      var sources = {
        darthVader: 'http://www.html5canvastutorials.com/demos/assets/darth-vader.jpg',
        yoda: 'http://www.html5canvastutorials.com/demos/assets/yoda.jpg'
      };

    [b]  loadImages(sources, function(images) {[/b]
        context.drawImage(images.darthVader, 100, 30, 200, 137);
        context.drawImage(images.yoda, 350, 55, 93, 104);
      });

    </script>
  </body>

Open in new window

Avatar of Tom Beck
Tom Beck
Flag of United States of America image

That's an example of a javascript closure.

http://www.javascriptkit.com/javatutors/closures.shtml

loadImages function takes two arguments, sources and callback.

The call to loadImages passes two arguments, sources, defined directly above the call, and the function(images) which is represented by the variable callback in the loadImages function. The "closure" allows the function argument inside the loadImages call to use the variable images from inside the loadImages function.
Avatar of jagguy

ASKER

i get what your saying but is there a better way to load multiple images on screen.
I dont like this code as you have to label each image a name and do some extra processing in function calls.
ASKER CERTIFIED SOLUTION
Avatar of Kishan Zunjare
Kishan Zunjare
Flag of Australia image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
In html5 canvas I can load 1 image. To load many images I look at this code
I am confused as to how this work with the callback

 loadImages(sources, function(images) {// where is function(images) to pass?

Did I misunderstand the question? I thought you were asking how the code works.

The accepted solution merely points to the code already posted. How is that a solution?