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:
- Use the File API to read in the image (you might do this in an
onchangelistener 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
- In your FileReader’s
onloadcallback (here,createImage), read theresultof 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):
- In your FileReader’s
onloadcallback (here,createImage), make a newImageobject and set itssrcto theresultof the FileReader:
img = new Image();
img.onload = imageLoaded;
img.src = fr.result;
- Finally, in your Image’s
onloadcallback, draw it to the canvas and then usecanvas.toDataUrlto 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