javascript - How can I draw an image from the HTML5 File API on Canvas? -


i draw image opened html5 file api on canvas.

in handlefiles(e) method, can access file e.target.files[0] can't draw image directly using drawimage. how draw image file api on html5 canvas?

here code have used:

<!doctype html> <html> <head> <meta charset="utf-8"/> <script> window.onload = function() {     var input = document.getelementbyid('input');     input.addeventlistener('change', handlefiles); }  function handlefiles(e) {     var ctx = document.getelementbyid('canvas').getcontext('2d');     ctx.drawimage(e.target.files[0], 20,20);     alert('the image drawn'); } </script> </head> <body> <h1>test</h1> <input type="file" id="input"/> <canvas width="400" height="300" id="canvas"/> </body> </html> 

you have file instance not image.

to contents of file, use filereader. pass contents image instance, can drawn on canvas: http://jsfiddle.net/t7mv6/.

to image, use new image(). src needs url referencing selected file. can use url.createobjecturl url referencing blob (a file blob): http://jsfiddle.net/t7mv6/86/.

var ctx = document.getelementbyid('canvas').getcontext('2d'); var img = new image; img.onload = function() {     ctx.drawimage(img, 20,20);     alert('the image drawn'); } img.src = url.createobjecturl(e.target.files[0]); 

note: sure revoke object url when done otherwise you'll leak memory. if you're not doing crazy, can stick url.revokeobjecturl(img.src) in img.onload function.

references:


Comments

Popular posts from this blog

linux - Using a Cron Job to check if my mod_wsgi / apache server is running and restart -

actionscript 3 - TweenLite does not work with object -

jQuery Ajax Render Fragments OR Whole Page -