Q:

Array of images in canvas not working

Could someone please help to make the below code work. also is there any other way to display the images without using onload?
<head id="Head1" runat="server">
    <meta name="viewport" content="width=device-width,initial-scale=1.0">
    <title></title>
<script src="//code.jquery.com/jquery-1.11.0.min.js"></script>

    <script type="text/javascript">
        $(document).ready(function () {

            var c = document.getElementById("myCanvas");
            c.width = $(document).width();
            c.height = $(document).height();
            var ctx = c.getContext("2d");
            var imgArray = new Array();

            imgArray[0] = new Image();
            imgArray[1] = new Image();
            imgArray[0].src = "1.png";
            imgArray[1].src = "2.png";
            var x = 30;
            var y = 40;
            for (var i = 0; i < 2; i++) {
                imgArray[i].onload = function () {

                    ctx.drawImage(imgArray[i], x, y);

                }
                x = x + 20;
            } 
        });

    </script>  
</head>

I want images to be displayed on canvas using array. it works fine if i use array without for loop. please help in fixing the issue.
<body style="margin:0; height:100%; width:100%; overflow:hidden;" >  
 <canvas id="myCanvas"  style="display:block; "   >
     Your browser does not support the HTML5 canvas tag.
  </canvas> 
</body>
</html>

A:

It's bad practice to define a function within a loop. Try defining it outside of the loop with a named function. Also it'd probably be better to set the src of the img after the onload function is attached. Something like:
$(document).ready(function () {

    var c = document.getElementById("myCanvas");
    c.width = $(document).width();
    c.height = $(document).height();
    var ctx = c.getContext("2d");
    var imgArray = new Array();

    imgArray[0] = new Image();
    imgArray[1] = new Image();
    var x = 30;
    var y = 40;

    function onImageLoad() {
        ctx.drawImage(this, x, y);
        x = x + 20;
    }

    for (var i = 0; i < 2; i++) {
        imgArray[i].onload = onImageLoad;
    } 

    imgArray[0].src = "1.png";
    imgArray[1].src = "2.png";
});

If you must have the loop in the function (which you don't), you would need to wrap it within a closure so that each image gets it's own onload function instead of defining the same function which is what happens in your case.
Something similar to the following would probably work:
for (var i = 0; i < 2; i++) {
    imgArray[i].onload = (function(idx) {
        return function() {
            ctx.drawImage(imgArray[idx], x, y);
            x = x + 20;
        }
    })(i)
} 

