javascript - Loading multiple images in Canvas -


i have problem displaying images in canvas. don't why it's rendering 1 image (background in case). here code:

    // ... code here      this.createbackground( canvas, config );     this.createplayer( canvas, config );    }    createbackground( element, config ) {     const canvas = element;     const ctx = canvas.getcontext( "2d" );      const bg = new image();     bg.src = "./img/" + config.bg;      bg.onload = () => {       ctx.drawimage( bg, 0, 0, config.width, config.height );     }      return bg;   }    createplayer ( element, config ) {     const canvas = element;     const ctx = canvas.getcontext( "2d" );      const player = new image();     player.src = "./img/" + config.character + "/run1.png";      player.onload = () => {       ctx.drawimage( player, 70, 310, player.width/3, player.height/3 );     }      return player;   } 

why player doesn't appear in canvas after bg method?

if have media dependent on other media, load media @ start , wait till have loaded before start using them.

for example following load array of images, using array of urls create , start load. counter counts each image loaded , when load count equal number of images function allloaded called.

const imageurl = ["foreground.jpg","background.jpg"]; // list of image urls const images = []; /// array hold images. var imagecount = 0; // number of loaded images;  // function called once images have loaded. function allloaded(){     // images have loaded , can rendered     ctx.drawimage(images[1],0,0); // draw background     ctx.drawimage(images[0],0,0); // draw foreground }  // iterate each image url, create, load, , add images array imageurl.foreach(src => {  // each image url      const image = new image();      image.src = src;      image.onload = ()=>{           imagecount += 1;          if(imagecount === imageurl.length){ // have loaded????              allloaded(); // call function start rendering          }      }      images.push(image); // add loading image images array  }); // image onload event not called until current execution // complete. 

Comments

Popular posts from this blog

ubuntu - PHP script to find files of certain extensions in a directory, returns populated array when run in browser, but empty array when run from terminal -

php - How can i create a user dashboard -

javascript - How to detect toggling of the fullscreen-toolbar in jQuery Mobile? -