1

*Update with link to question I reference If I load multiple images with the for loop, do I only need one img.onload function?
I want to bring in many image files to use in canvas via an array of all the images (that way they load before I need them), Using a solution found on here I'm getting the error

"Uncaught TypeError: Cannot read property 'drawImage' of undefined at Image. (app.js:32)"
line 32 would be canvasContext[value].drawImage(images[i], 0, 0);

Obviously, I didn't understand the solution because I'm kind of at a loss as to what is causing this.
The end result would be for me to set up all the images on load and then in the draw function I have, declare their positions and sizing.

window.onload = function() {
console.log(keysDown);
canvas = document.getElementById('myCanvas');
canvasContext = canvas.getContext('2d');
var images = ['Frylock.png', 'Master_Shake.png'];

// Assign onload handler to each image in array
for (var i = 0; i <= images.length; i++) {

    var img = new Image();
    img.onload = (function(value) {
        return function() {
            canvasContext[value].drawImage(images[i], 0, 0);
        }
    })(i);

    // IMPORTANT - Assign src last for IE
    img.src = './' + images[i];
}
Shane
  • 31
  • 4

0 Answers0