如何使用 Fabric.js 将图像上传到画布?

我希望它创建一个流程,用户可以在其中上传他们的图像,然后在浏览器中使用 Fabric.js 使用一些按钮在浏览器中编辑它们,该按钮使用 Fabric.js 添加一些效果.

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.

我无法让它工作.我的 HTML 是:

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

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

JavaScript 如下:

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);
    });
}); 

推荐答案

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]);
}

相关文章