How to upload an image to a canvas with Fabric.js?

user1230041 picture user1230041 · Feb 12, 2014 · Viewed 21.7k times · Source

I want that to create a process where the users can upload their images and then edit them in the browser in a Canvas with Fabric.js using some buttons, which uses Fabric.js to add some effects.

I can't make it work. My HTML is:

<form id="uploadImg" runat="server">
  <input type="file" id="uploadedImg"/>
</form>
<canvas id="canvas"></canvas>

The JavaScript is the following:

var canvas = new fabric.Canvas('canvas');
canvas.setHeight(480);
canvas.setWidth(640);

$('#uploadedImg').change(function () {
    var imgData = $(this).files[0];
    fabric.util.loadImage(imgData, function(img) {
        var oImg = new fabric.Image(img);
        oImg.scale(0.2).set({
            left: 100,
            top: 100,
        });
    canvas.add(oImg);
    });
}); 

Answer

samad picture samad · Apr 2, 2014
document.getElementById('imgLoader').onchange = function handleImage(e) {
var reader = new FileReader();
  reader.onload = function (event){
    var imgObj = new Image();
    imgObj.src = event.target.result;
    imgObj.onload = function () {
      var image = new fabric.Image(imgObj);
      image.set({
            angle: 0,
            padding: 10,
            cornersize:10,
            height:110,
            width:110,
      });
      canvas.centerObject(image);
      canvas.add(image);
      canvas.renderAll();
    }
  }
  reader.readAsDataURL(e.target.files[0]);
}