0

I have several canvases. I also have several picture URLs. I want to draw all pictures on the canvas. There is a problem in the drawing function. Drawing the image only works when the image loads completely, but I have to draw the image as it loads. I wrote following code:

for (var i = 2; i < length; i++) {
    canvid[i] = "canv" + i;
    img[i] = new Image();

    img[i].src = "..\\images\\UploadImage\\"+ name + i + ".jpg";

    img[i].onload = function () { 
        var c = document.getElementById(canvId[i]);
        var cDraw = c.getContext("2d");
        cDraw.drawImage(img[i], 0, 0);
    };

I know this code has error, it's kind of pseudo code to show what I want.

Mad Physicist
  • 107,652
  • 25
  • 181
  • 264
farham heidari
  • 157
  • 2
  • 9

2 Answers2

0

Put your logic in

$(documet).ready(function(){

   //logic
});
Sagar
  • 642
  • 3
  • 14
0

the answer is in following link

stack overflow link

when you want to call on click event on image variable you have to wait for it so you couldn't use loop you have to put next call on previous image on load event .

 var loadImages = function (imageURLarray) {
                if (!(startPage < pages))
                    return;
                canvid = "canv" + i;
                img.src = imageURLarray[startPage];
                // your top code
                img.onload = function (e) {
                    // code, run after image load
                    var c = document.getElementById(canvid);
                    var cDraw = c.getContext("2d");
                    cDraw.drawImage(img, 0, 0);
                    startPage++;
                    loadImages(imageURLarray);
                }
            }

            loadImages(imageURLarray);
Community
  • 1
  • 1
farham heidari
  • 157
  • 2
  • 9