Alejandro Gorgal
Alejandro Gorgal

Reputation: 303

HTML5 Canvas: I'm trying to load an image to the canvas

I'm trying to setup a canvas where the user can load a custom image. As far as I can tell everything should be set but for some reason it is not working.

Here's my jsfiddle.

HTML:

<canvas id="image-canvas" width="500" height="500" style="border:1px solid grey"></canvas>
<input type='file' id='fileInput' />

Javascript:

var canvas = document.getElementById('image-canvas');
ctx = canvas.getContext('2d');

// Trigger the imageLoader function when a file has been selected
var fileInput = document.getElementById('fileInput');
fileInput.addEventListener('change', imageLoader(), false);

function imageLoader() {
    var reader = new FileReader();
    reader.onload = function(event) {
      img = new Image();
      img.onload = function(){
        ctx.drawImage(img,0,0);
      }
      img.src = reader.result;
    }
    reader.readAsDataURL(fileInput.files[0]);
   }

Upvotes: 1

Views: 53

Answers (2)

unobf
unobf

Reputation: 7254

One line is wrong. Here is the fixed line:

fileInput.addEventListener('change', imageLoader, false);

Upvotes: 1

Thierry
Thierry

Reputation: 5243

You are calling imageLoader, not passing as a function to call.

Replace

fileInput.addEventListener('change', imageLoader(), false);

by

fileInput.addEventListener('change', imageLoader, false);

Upvotes: 4

Related Questions