HTML5 Canvas toDataURL returns blank

My intuition says that everything from var imageData = … should go into the img.onload function.

That means, at the relevant part the code becomes:

img.onload = function() {
  canvas.width = width;
  canvas.height = height;
  ctx.drawImage(img, 0, 0, width, height);

  var imageData = ctx.getImageData(0, 0, canvas.width, canvas.height);

  document.body.appendChild(canvas); //picture gets uploaded                    

  // Generate the image data

  var Pic = canvas.toDataURL("image/png");

  console.log(Pic); // => returns base64 value which when tested equivalent to blank                              
  Pic = Pic.replace(/^data:image\/(png|jpg);base64,/, "")

  // Sending image to Server
  $.ajax({
    // …
  });
};
img.src = datauri;

The reason is that the line

ctx.drawImage(img, 0, 0, width, height);

correctly executes after the image has been loaded. But unfortunately, you don’t wait for loading when this line gets executed:

var imageData = ctx.getImageData(0, 0, canvas.width, canvas.height);

and all subsequent lines.

The image needs to be loaded in order to draw it on the canvas. The canvas needs to contain the loaded image in order to call getImageData.

Leave a Comment