Can I load a local file into an html canvas element?

I have a functioning fiddle (based on the prior work of this answer) that demonstrates how to upload an image using a file input, place it inside a canvas, and read the base64 data URL back out.

In short, you should:

  1. Use the File API to read in the image (you might do this in an onchange listener of the input element):
var file = input.files[0];
var fr = new FileReader();
fr.onload = createImage;   // onload fires after reading is complete
fr.readAsDataURL(file);    // begin reading
  1. In your FileReader’s onload callback (here, createImage), read the result of the FileReader (here, fr.result). That’s your image data URL!

OPTIONAL STEPS (only needed if you plan to manipulate the images on a canvas):

  1. In your FileReader’s onload callback (here, createImage), make a new Image object and set its src to the result of the FileReader:
img = new Image();
img.onload = imageLoaded;
img.src = fr.result;
  1. Finally, in your Image’s onload callback, draw it to the canvas and then use canvas.toDataUrl to the data:
canvas.width = img.width;      // set canvas size big enough for the image
canvas.height = img.height;
var ctx = canvas.getContext("2d");
ctx.drawImage(img,0,0);         // draw the image

// do some manipulations...

canvas.toDataURL("image/png");  // get the data URL

Leave a Comment