title: Canvas React. Is there a better way to call a function multiple images onload?
body: <p>Here is part of my React code. It works with canvas.</p>
  
  <pre><code>    componentDidMount(){                
              var canvas = document.getElementById("canvas");     
              var ctx = canvas.getContext("2d");    
              ctx.fillStyle="#000";
              ctx.fillRect(0,0,2800,2800);
              ctx.fillStyle="#eee";
              ctx.fillRect(150,150,2500,2500);        
              var board = this.generateBoard(ctx);     
              var createImage = function(src){
                  var img = new Image();
                  img.src = src;
                  return img;
              }   
              var images = {
                  "hero-right": createImage("../../images/hero-right.png"),
                  "hero-left": createImage("../../images/hero-left.png"),
                  "treasure": createImage("../../images/treasure.png")
              };        
              var imageCount = Object.keys(images).length;        
              var imagesLoaded = 0;
  
              for(var key in images){            
                  images[key].onload = function(){
                      imagesLoaded++;                
                      if(imagesLoaded == imageCount){                    
                          startGame();
                      }
                  };
              }
  
              var startGame = function(){            
                  this.setState({
                          ctx: ctx,
                          board: board,
                          hero:{
                              img: images["hero-right"],
                              x: 0,
                              y:0
                          }            
                      },
                      ()=&gt;{this.placeItems()}
                  );
              }.bind(this)          
          },
  
          placeItems(){
              this.placeHero();
          },
  </code></pre>
  
  <p>The problem was - I need to call this piece of code:</p>
  
  <pre><code>           this.setState({
                      ctx: ctx,
                      board: board,
                      hero:{
                          img: images["hero-right"],
                          x: 0,
                          y:0
                      }            
                  },
                  ()=&gt;{this.placeItems()}
              );
  </code></pre>
  
  <p>after all of my images loaded.
  I managed to do that. But it's ugly. Please help me to make it better.</p>