0

I'm trying to load a bunch of images onto a canvas, but non of them are appearing. The sources contain the links to the images I want to use. Anyone have any ideas?

This is my first time working with canvas.

    <canvas id ="canvas" width = "500" height = "500"></canvas>
    <script>

    var c = document.getElementById("canvas");
    var ctx = c.getContext("2d");

    loadImages(ctx);

    function loadImages()
    {
        var c = document.getElementById("canvas");
        var ctx = c.getContext("2d");

            var number = 0;
            var bX = 0;
            var bY = 0;
            var images = [];
            images = getImages();

            for(var i = 0;i<images.length;i++){
                var t = images[i];
                document.write(t.src+"<br>");
                ctx.drawImage(t,0,0,100,100);
                if(i%4==0)
                {
                    bX = 0;
                    bY -= 110;
                }
                else
                {
                    bX+=110;
                }

            }

    }

I did this function to preload the images and return them in an array

    function getImages()
    {
        var imgList = [];
        var sources = 
        [             "http://terminus.scu.edu/~ntran/csci168-f15/hw/hw3/tile_00.png",
                      "http://terminus.scu.edu/~ntran/csci168-f15/hw/hw3/tile_01.png",
                      "http://terminus.scu.edu/~ntran/csci168-f15/hw/hw3/tile_02.png",
                      "http://terminus.scu.edu/~ntran/csci168-f15/hw/hw3/tile_03.png",
                      "http://terminus.scu.edu/~ntran/csci168-f15/hw/hw3/tile_04.png",
                      "http://terminus.scu.edu/~ntran/csci168-f15/hw/hw3/tile_05.png",
                      "http://terminus.scu.edu/~ntran/csci168-f15/hw/hw3/tile_06.png",
                      "http://terminus.scu.edu/~ntran/csci168-f15/hw/hw3/tile_07.png",
                      "http://terminus.scu.edu/~ntran/csci168-f15/hw/hw3/tile_08.png",
                      "http://terminus.scu.edu/~ntran/csci168-f15/hw/hw3/tile_09.png",
                      "http://terminus.scu.edu/~ntran/csci168-f15/hw/hw3/tile_10.png",
                      "http://terminus.scu.edu/~ntran/csci168-f15/hw/hw3/tile_11.png",
                      "http://terminus.scu.edu/~ntran/csci168-f15/hw/hw3/tile_12.png",
                      "http://terminus.scu.edu/~ntran/csci168-f15/hw/hw3/tile_13.png",
                      "http://terminus.scu.edu/~ntran/csci168-f15/hw/hw3/tile_14.png" ];
            var s = 0;
            var length = sources.length;
            for(s; s< length;++s)
            {
                imgList[s] = new Image();
                imgList[s].src = sources[s];
            }
            return imgList;
        }


    </script>
</body>



</html>
2
  • It appears you intended to use bX and BY as arguments to drawImage. Using bY -= 110 makes bY negative the first time the condition is met, which is the first iteration since 0%0==0. Oct 20, 2015 at 4:39
  • 1
    Don't use document.write, it has a lot of problems and there are better alternatives. If you are just using it for debugging, use console.log instead. One of the problems that document.write has is that if you call it after the page is loaded, it will wipe out everything on the page and replace it. That means if you call loadImages after the page has loaded, everything, including the canvas tag will be lost and because of that your code will stop working at all. Oct 20, 2015 at 5:28

3 Answers 3

1

First of all, make sure that the images are retrieved and loaded properly. Then adjust your code to something like below:

   for (var i = 1; i <= images.length; i++) {
       var t = images[i];
       document.write(t.src+"<br>");
       ctx.drawImage(t,bX,bY,100,100);
       if (i%4 === 0) {
           bX = 0;
           bY += 110;
       }
       else {
           bX += 110;
       }
   }

You want to iterate from index 1 instead of 0, so that the if statement i % 4 === 0 is not fulfilled right off the bat. Then you want to use the variables bX and bY as the position offsets from the images. You used ctx.drawImage(t,0,0,100,100); before which stacked all the images in the same position. And finally, increment bY in order to push the images down.

0

The problem is that the images arent loading before you try to draw them. You should create the imgs and append them to the body

images = getImages();

for(var i = 0; i<images.length; i++){
    var img = document.createElement("img");
    img.src= images[i].src;
    document.body.appendChild(img);
    img.style.display = "none";
    img.id="img"+String(i);
}

then draw them like this

loadImages(images);

function loadImages(images){
    var c = document.getElementById("canvas");
    var ctx = c.getContext("2d");

    for(var i = 0;i<images.length;i++){
            ctx.drawImage(document.getElementById("img"+String(i)),i*10,0,100,100);
            if(i%4==0)
            {
                bX = 0;
                bY -= 110;
            }
            else
            {
                bX+=110;
            }

        }

}

I tested it out and it worked

3
  • also change the name loadImages to drawImages, it's more coerent, The images load when appended to the body and then are draw onto the canvas Oct 20, 2015 at 4:41
  • "img" + i will coerce i to a string, you don't really need to use the String constructor. It just adds more noise, making the code harder to read. It also makes the script longer (and thus it will download slower). Oct 20, 2015 at 5:35
  • Also, appending the image element to the DOM before you draw it to the canvas does not guarantee that the image will finish downloading before you try to draw it. Image loading is asynchronous. Oct 20, 2015 at 8:17
0

It is not working, among other reasons, because you are not waiting for the images to load before you try to use them. You can do this using the Image object's load event. I would have written it something like this, using Promises to manage the loading state.

var images,
  nameList = document.getElementById('image-names'), // just a div to display the stuff you were writing out to document. write.
  // this function returns a Promise which will resolve once all of the
  // images are done loading
  preloadImages = function () {
    var imagePromises,
      sources = [
        "http://terminus.scu.edu/~ntran/csci168-f15/hw/hw3/tile_00.png",
        "http://terminus.scu.edu/~ntran/csci168-f15/hw/hw3/tile_01.png",
        "http://terminus.scu.edu/~ntran/csci168-f15/hw/hw3/tile_02.png",
        "http://terminus.scu.edu/~ntran/csci168-f15/hw/hw3/tile_03.png",
        "http://terminus.scu.edu/~ntran/csci168-f15/hw/hw3/tile_04.png",
        "http://terminus.scu.edu/~ntran/csci168-f15/hw/hw3/tile_05.png",
        "http://terminus.scu.edu/~ntran/csci168-f15/hw/hw3/tile_06.png",
        "http://terminus.scu.edu/~ntran/csci168-f15/hw/hw3/tile_07.png",
        "http://terminus.scu.edu/~ntran/csci168-f15/hw/hw3/tile_08.png",
        "http://terminus.scu.edu/~ntran/csci168-f15/hw/hw3/tile_09.png",
        "http://terminus.scu.edu/~ntran/csci168-f15/hw/hw3/tile_10.png",
        "http://terminus.scu.edu/~ntran/csci168-f15/hw/hw3/tile_11.png",
        "http://terminus.scu.edu/~ntran/csci168-f15/hw/hw3/tile_12.png",
        "http://terminus.scu.edu/~ntran/csci168-f15/hw/hw3/tile_13.png",
        "http://terminus.scu.edu/~ntran/csci168-f15/hw/hw3/tile_14.png" 
    ];

    // if we have already loaded and cached the images,
    // return them right away wrapped in a resolved Promise
    if (images) {
      nameList.innerHTML += 'Using cached images.<br>';
      return Promise.resolve(images);
    }

    // otherwise we use .map to iterate over the items in sources and
    // create a new array of promises and store them in imagePromises
    imagePromises = sources.map(function (src) {
      // each of the promises that are created by this function
      // are stored in imagePromises and will resolve when the image
      // it represents fires its load event
      return new Promise(function (resolve, reject) {
          var img = new Image();

          // once the image has loaded, resolve its Promise
          img.onload = function () {
            resolve(img);
          };
          // if there is an error reject this image's Promise
          img.onerror = function () {
            reject(src + ' failed to load.');
          };

          img.src = src;
      });
    });

    // Promise.all will create a Promise that will resolve when all of the
    // images are loaded (because all of the Promises representing those
    // images will have resolved). If there is an error loading any of the
    // images it will be rejected, which we can handle later.
    return Promise.all(imagePromises)
      // after Promise.all returns a resolved Promise, we create a new Promise
      // using .then, which is what actually gets returned by preloadImages.
      .then(function (loadedImages) {
        // cache the loaded images in case we need them later
        images = loadedImages;
        // return the images so that anything chained off of this Promise
        // has access to them.
        return loadedImages;
      });

  },
  displayImages = function () {
    var c = document.getElementById("canvas"),
      ctx = c.getContext("2d"),
      bX = 0,
      bY = 0;

    // preloadImages will return a Promise that will resolve once all of the
    // images have been loaded. The .then chained off of that Promise receives
    // the list of images via the images parameter
    preloadImages().then(function (images) {
      var i,
        img;

      for(i = 0; i < images.length; /* no increment expression, see below */) {
          img = images[i];
          nameList.innerHTML += img.src + "<br>";
          ctx.drawImage(img, bX, bY, 100, 100); // you need to make sure to
                                                // use your offset here

          // incrementing here instead of in the increment expression of
          // for statement makes this part work correctly
          i += 1;

          if (i % 4 === 0) {
              bX = 0;
              bY += 110;
          } else {
              bX += 110;
          }
      }
    }).catch(function (msg) {
      // if there was an error loading any of the images, this .catch
      // will display an error
      nameList.innerHTML += msg + '<br>';
    });
};

displayImages();

There is a working fiddle here. If you add a non-existent image to your sources list you will notice that it displays an error message instead of drawing to the canvas.

You don't have to use Promises, you could instead make preloadImages take a callback as an argument and then call that once all of the images are loaded. In that case you would have to manually keep track of how many images have been loaded and in the load event of each image check to see if all the images are loaded before calling the callback.

My coding style might look a bit strange to you since I make it a habit to use function expressions instead of function statements and a few other things like the strict equals operator (===). I would recommend Douglas Crockford's book JavaScript: The Good Parts if you would like to know more about this style of coding and why I use it. (It is a great book and I recommend it even if you don't.)

Not the answer you're looking for? Browse other questions tagged or ask your own question.