title: How can I set an HTML5 canvas ImageData from an XMLHttpRequest response?
body: <p>I would like to use XMLHttpRequest to load a png file and then use the response to set the image data in a canvas object, thus totally eliminating the need for an Image object and having direct access to the ImageData. So far my code looks like this:</p>
  
  <pre><code>var xhr = new XMLHttpRequest();
  var context = document.createElement("canvas").getContext("2d"); // the context for the image we are loading
  var display = document.getElementById("display").getContext("2d"); // the context of the canvas element in the html document
  
  function load(event) {
    var imagedata = context.createImageData(64, 64); // 64 = w, h of image
    imagedata.data.set(new Uint8ClampedArray(this.response)); // the response of the load event
    context.putImageData(imagedata,0,0); // put the image data at the top left corner of the canvas
  
    display.drawImage(context.canvas, 0, 0, 64, 64, 0, 0, 64, 64); // draws a bunch of jumbled up pixels from my image in the top of my display canvas
  }
  
  xhr.addEventListener("load", load);
  xhr.open("GET", "myimage.png");
  xhr.responseType = "arraybuffer";
  xhr.send(null);
  </code></pre>
  
  <p>What am I doing wrong here? is it a problem with converting the ArrayBuffer in the response to a Uint8ClampedArray? Should I be using different array types? Is it the XMLHttpRequest? Is this possible?</p>