Results 1 to 3 of 3

Thread: Using a JavaScript while loop to draw images to canvas

  1. #1
    Join Date
    Apr 2012

    Using a JavaScript while loop to draw images to canvas


    I have the following JavaScript while loop, which I want to use to draw ten .png images to the HTML5 canvas:

                                     while(fileName < 11){
    				/*Create an array of images here, move to next element of array on each iteration */
    					var numbers = new Array();
    					numbers[0] = "1.png"
    					image.onload = function(){
    						context.drawImage(image, imageX, imageY, 50, 50);
    					image.src = fileName+".png";
    					fileName = fileName+1;
    					imageX = imageX+50;
    					console.dir(fileName); /* displays in the console- helpful for debugging */
    However, when I view my page in the browser at the moment, and click the button that calls this while loop, only the last image is displayed... it is displayed in the correct location (i.e. the variable imageX, which is the x location of where the image is to be drawn has been updated)

    What I intended was that the loop would load the first image, 1.png, and draw it to the canvas at the location imageX, imageY; it would then increment the value of the imageX variable, increment the value of the variable I am using to hold the filename, load the next image, 2.png, and draw it in the new location... then repeat these steps until all 10 images had been drawn in a row on the canvas.

    Could someone please point out to me what I'm doing wrong here, and how I can correct it?

    Many thanks

  2. #2
    Join Date
    Aug 2007
    It would be better if you didn't simply repost your original post a few weeks later after not replying to any post on your first one!

    Best of luck!

  3. #3
    Join Date
    Apr 2012
    Sorry, completely forgot I had posted already!

Thread Information

Users Browsing this Thread

There are currently 1 users browsing this thread. (0 members and 1 guests)

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
HTML5 Development Center