Saturday, 8 June 2013

Load multiple images in EaselJS

I will be loading multiple images in EaselJS using PreloadJS to load the assets before adding them to the stage. Here is a quick example.

<!doctype html>
<html>
<head>
    <meta charset="UTF-8">
 <style> 
    #canvas{border: 1px solid #999999;} 
    </style> 
 <script src="easeljs.js"></script> 
 <script src="preloadjs.js"></script> 
</head>
<body onload="init()">
 <canvas id="canvas" width="640" height="480"></canvas>
 <script>
  var queue, stage;
  
  function init()
  {
   //preload
   queue = new createjs.LoadQueue();
   queue.addEventListener('complete', completeHandler);
   queue.loadManifest([
     {id:"picture1", src:"picture1.png"},
     {id:"picture2", src:"picture2.png"},
     {id:"picture3", src:"picture3.png"}
   ]);
  }
  
  function completeHandler()
  { 
   //setup createjs
   stage = new createjs.Stage('canvas');
   createjs.Ticker.setFPS(60);
   createjs.Ticker.addEventListener("tick", tick);
   
   //add bitmaps
   var bp1 = new createjs.Bitmap(queue.getResult('picture1'));
   bp1.x = 100;
   bp1.y = 50; 
   stage.addChild(bp1);  
            
   var bp2 = new createjs.Bitmap(queue.getResult('picture2'));
   bp2.x = 200;
   bp2.y = 50; 
   stage.addChild(bp2);           
            
   var bp3 = new createjs.Bitmap(queue.getResult('picture2'));
   bp3.x = 200;
   bp3.y = 50; 
   stage.addChild(bp3);

  }
   
  function tick(e)
  {
   stage.update();
  }
 </script>
</body>
</html>



If you have many images you can use a For-loop to iterate though the id’s in the manifest instead of adding the bitmap images separately on the stage.

<!doctype html>
<html>
<head>
    <meta charset="UTF-8">
 <style> 
    #canvas{border: 1px solid #999999;} 
    </style> 
 <script src="easeljs.js"></script> 
 <script src="preloadjs.js"></script>
</head>
<body onload="init()">
 <canvas id="canvas" width="640" height="480"></canvas>
 <script>
  var queue, stage, manifest;
  
  function init()
  {
   //manifest
   manifest = [
     {id:"picture1", src:"picture1.png"},
     {id:"picture2", src:"picture2.png"},
     {id:"picture3", src:"picture3.png"}
   ];
            
   //setup createjs
   stage = new createjs.Stage('canvas');
   createjs.Ticker.setFPS(60);
   createjs.Ticker.addEventListener("tick", tick);
            
   //preload
   queue = new createjs.LoadQueue();
   queue.addEventListener('complete', completeHandler);
   queue.loadManifest(manifest);
  }
  
  function completeHandler(e)
  {   
    //add bitmap on stage
    for(var i = 0; i < manifest.length; i++){         
      var bp = new createjs.Bitmap(manifest[i].src);
      bp.x = i * 100;
      bp.y = 200;
      stage.addChild(bp);
    }
  }
   
  function tick(e)
  {
   stage.update();
  }
 </script>
</body>
</html>

If there are a large number of images you can use the progress event to show the overall progress of the loading items.

0 comments:

  COPYRIGHT © 2014 · ILIKE2FLASH · Theme by Ourblogtemplates

Back to TOP