0

I am working on an animated avatar.

I first pull in the frame details of the avatar from some XML.

I need to trigger the frames individually so that I can animate the avatar but the array the frames are stored in ends up empty where I need it.

var canvas = document.getElementById('myCanvas');
var context = canvas.getContext('2d');
var flagImagesLoaded = false;

findImages();

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

function findImages() {
    var sources = {};

    $.ajax({
        type: 'GET',
        url: 'image_loader.php?avatar=jess',
        dataType: 'xml',
        success: function(xml) {
            $(xml).find('frame').each(function() {
                var name = $(this).find("name").text().toString();
                var url = $(this).find("url").text().toString();
                sources[name] = url;
            });

            loadImages(sources, function(images) {
                context.drawImage(images.v1, 0, 0);
            });
        }
    });
}

console.log(images);
context.drawImage(images.v5, 0, 0);

That is my code. If you look at the 'findImages' function you will see that it calls 'loadImages' which loads the image names (key) and url into the 'images' array.

Once loaded this part correctly displays the starting image of the avatar :

context.drawImage(images.v1, 0, 0);

All well and good. But when I try to access the 'images' array outside of the function like so (as per code above) :

console.log(images);
context.drawImage(images.v5, 0, 0);

The console reports an empty object and I get the error :

Uncaught TypeError: Failed to execute 'drawImage' on 'CanvasRenderingContext2D': The provided value is not of type '(HTMLImageElement or HTMLVideoElement or HTMLCanvasElement or ImageBitmap)'

I think this is a problem with scope perhaps ?

thefourtheye
  • 233,700
  • 52
  • 457
  • 497
Rog
  • 458
  • 1
  • 4
  • 13
  • 3
    It's not a problem with scope. Your `findImages()` function makes an **asynchronous** ajax call, so those `console.log()` calls at the end happen long before the code in the "success" handler runs. – Pointy Mar 07 '15 at 16:19
  • @Pointy, that's it. I added a flag and timer to trigger the frame after the ajax is done and it works. Many thanks. – Rog Mar 07 '15 at 16:26

0 Answers0