title: How can I cycle through images in javascript to do some image processing?
body: <p>I want to cycle through a list of images.
  For each image, I'm trying to display it on a canvas, and to extract some information from it - in this example, it is as simple as it's width. The problem is that only the last image is displayed, and the values for the width are always undefined.</p>
  
  <pre><code>&lt;!DOCTYPE html&gt;
  &lt;html&gt;
  &lt;head lang="en"&gt;
  &lt;meta charset="UTF-8"&gt;
  &lt;/head&gt;
  &lt;body&gt;
  
  &lt;canvas id="canvas" width="100" height="100"&gt;&lt;/canvas&gt;
  &lt;script&gt;
      var canvas = document.getElementById("canvas");
      var ctx = canvas.getContext('2d');
      var paths = ['images/people/img_1.jpg', 'images/people/img_2.jpg', 'images/people/img_3.jpg'];
      var width = new Array(3);
  
      processImages();
  
      function processImages() {
  
          function display(img, i) {
              canvas.width = img.width;
              canvas.height = img.height;
              ctx.drawImage(img, 0, 0);
              width[i] = img.width;
              alert("i = " + i);
          }
  
          for (var i = 0; i &lt; 3; i++) {
              var img = new Image();
  
              img.onload = (function (x) {
                  return function() {
                      display(this, x);
                  }
              })(i);
  
              img.src = paths[i];
          }
  
          for (i = 0; i &lt; 3; i++) {
              document.write("&lt;br&gt;Image " + i + " width is: " + width[i]);
          }
      }
  &lt;/script&gt;
  
  &lt;/body&gt;
  &lt;/html&gt;
  </code></pre>