Hi,

This error must be silly but i just can't seem to get over it for a day now.
The following code tries to fill up an image array, and then "do something" with it.
The problem is that I get an undefined error for the use of icons[i].src the next line (line 24) after a value was assigned to it.

Can anyone look and see what I'm doing wrong?
Thanks!

<!DOCTYPE HTML>
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
        <title>New Web Project</title>
        <script>

            //Parameters ("constants")
            var iconsNumber = 13;                           //The number of available icons (letters+other) that need to be loaded and played with
            var path ='http://127.0.0.1:8020/Switch/';              

            //Global Variables
            var c;                                          //contains the canvas
            var gameBoard;                                  //handles draw methods on the canvas
            var bg = new Image();                           //variable to contain the bg image
            var icons = [];                                 //an array binding icons with icon images to be used
            var boardTiles =[];                             //contains the tile array, and which icon is on what tile.

                for(var i=0;i<iconsNumber;i++)               //fill the icons array with n icons.
                {
                    icons[i]= new Image;
                    icons[i].src = path+i+".png";
                    icons[i].onload = function() {
                    document.getElementById("debug").innerHTML= ("<img src='"+icons[i].src+"'></img>"+icons[i].src); //debug code
                    };
                }
         </script>
    </head>
    <body>
       <canvas id="gameCanvas" width="1280" height="720" style="border:1px solid #c3c3c3;">
            Your browser does not support HTML5.
        </canvas>
            <BR>Draw Icon:<BR>
        <section>
            <p id='debug'>Debug data:<BR></p> <!--debug paragraph-->
    </section>
    </body>
</html>

Recommended Answers

All 2 Replies

Change icons[i].src to this.src

Note that you are inside the function of icons[i] by icons[i].onload = function()

Here's a small example:

<html>
<head>
    <title></title>
    <script>
        var img = [];
        for (i = 0;i<3;i++){
            img[i] = new Image;
            img[i].src = "b.png"; //assuming you have a b.png img
            img[i].onload = function(){
                alert(this.src);
                //alert(img[i].src); would generate an error - function scope
            };
        }
    </script>
</head>
<body>

</body>
</html>

Much Thanks! So Wow! Such Thrilled!
It worked!

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.