Skip to content

Instantly share code, notes, and snippets.

@felixzapata
Created September 9, 2012 12:44
Show Gist options
  • Save felixzapata/3684117 to your computer and use it in GitHub Desktop.
Save felixzapata/3684117 to your computer and use it in GitHub Desktop.
load an image from an input file into canvas tag
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");
}
};
}
@Caster101
Copy link

And there is many other issues in this code we have to upload twice to upload a single image some time image didn't show up

@dominicwhite
Copy link

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.

@TellTheL
Copy link

TellTheL commented Oct 4, 2020

THANK YOU SO MUCH!!!!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment