Created
September 9, 2012 12:44
-
-
Save felixzapata/3684117 to your computer and use it in GitHub Desktop.
load an image from an input file into canvas tag
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function loadCanvasWithInputFile(){ | |
// canvas | |
var canvas = document.getElementById('myCanvas'); | |
var context = canvas.getContext("2d"); | |
var fileinput = document.getElementById('ab'); // input file | |
var img = new Image(); | |
fileinput.onchange = function(evt) { | |
var files = evt.target.files; // FileList object | |
var file = files[0]; | |
if(file.type.match('image.*')) { | |
var reader = new FileReader(); | |
// Read in the image file as a data URL. | |
reader.readAsDataURL(file); | |
reader.onload = function(evt){ | |
if( evt.target.readyState == FileReader.DONE) { | |
img.src = evt.target.result; | |
context.drawImage(img,100,100); | |
} | |
} | |
} else { | |
alert("not an image"); | |
} | |
}; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
The loading problem mentioned by @Caster101 can be fixed by replacing line 18 with:
img.onload = () => cxt.drawImage(img, 100, 100);
to wait to draw the image until after it has loaded.