K. D. K. D. - 1 year ago 165
HTML Question

Draw raw-image into canvas

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


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

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

Here is my javascript that handles the picture after upload:

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

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 Source

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.onload = function(e) {
    var img = new Image();
    img.onload = function() {
       context.drawImage(img, 100,100)
    img.src = e.target.result;
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download