title: Javascript using callback to draw an image to canvas
body: <p>I think I'm having a similar issue to <a href="https://stackoverflow.com/questions/19546035/canvas-drawimage-not-drawing-image-to-canvas">this question</a>, but I would like a little help understanding how to use a callback function and how to implement it for my particular situation. I'm trying to have an image get drawn to a canvas "on demand", i.e. any time a certain function is called. The image is associated with an object I call a Block. A Block has dimensions, coordinates, and a url.</p>
  
  <pre><code>var canvas = document.getElementById("myCanvas");
  var context = canvas.getContext("2d");
  
  function Block(x, y, width, height, url) {
          this.x = x;
          this.y = y;
          this.width = width;
          this.height = height;
          this.url = url;
          this.drawBlock = drawBlock;
          function drawBlock() {
                var blockSprite = new Image();
                blockSprite.src = url;
                blockSprite.onload = context.drawImage(blockSprite,x,y,width,height);
          }
    }
  </code></pre>
  
  <p>You can see a demo <a href="http://jsfiddle.net/h7pbx/1/" rel="nofollow noreferrer">here</a>. Oddly enough, it works if I link to an image on the web, but fails if I link to an image on my disk. I believe that this is because the onload event occurs before drawBlock is called, and that I need to use callbacks or promises to fix this, but I'm very new to Javascript so I'd like a little guidance here. Any help or advice would be appreciated.</p>