K. D. K. D. - 2 months ago 20
HTML Question

Draw raw-image into canvas

I want to put an uploaded picture into a canvcas to work with it.

HTML:

<h2>Upload:</h2>
<input type="file" id="take-picture" accept="image/*">

<h2>Preview:</h2>
<p>
<canvas id="show-picture" style="background-color: aqua; height: 100px; width: 100px;" />
</p>


Here is my javascript that handles the picture after upload:

takePicture.onchange = function (event) {
var files = event.target.files,
file;
if (files && files.length > 0) {
file = files[0];
processImage(file);
}
};


Now in the processImage-method the picture should be stored within a canvas.

function processImage(file) {
// showImage(showPicture, file); //loading into a regular img-tag

var canvas = document.getElementById('show-picture');
var context = canvas.getContext('2d');
context.drawImage(file, 100, 100);
}


I was able to put this file into an img-tag but I can't simply draw it.

Can you help me?

Answer

The drawImage function takes an img element as input, not a file.

So you need to create an img element from the file (but you don't need to append it to the document). And when the image has finished loading (there's an onload event), you can draw it on the canvas.

EDIT: You also need to read the content of the file as a data url before setting it as the image src.

var reader = new FileReader();
reader.readAsDataUrl(file)
reader.onload = function(e) {
    var img = new Image();
    img.onload = function() {
       context.drawImage(img, 100,100)
    }
    img.src = e.target.result;
}