如何使用fabricjs从HTMlL5画布中的本地硬盘上传图像文件

时间:2015-02-03 11:00:40

标签: javascript html5 html5-canvas fabricjs

 <html>
<input type="file" name="Image">
</html>

<script>
fabric.Image.fromURL('image.jpg', function(img) {enter code here
var oImg = img.set({ left: 50, top: 100, angle: 00 }).scale(0.9);
canvas.add(oImg).renderAll();
canvas.setActiveObject(oImg);
});
</script>

我试图通过输入标签从硬盘上传图像文件。这是我的示例代码。告诉我如何更改此脚本以便我可以从输入中选择图片。

4 个答案:

答案 0 :(得分:6)

您可以使用HTML5 FileReader查看图像而不上传图像并将其添加到画布。

&#13;
&#13;
var canvas = new fabric.Canvas('canvas');

document.getElementById('file').addEventListener("change", function(e) {
    var file = e.target.files[0];
    var reader = new FileReader();
    reader.onload = function(f) {
        var data = f.target.result;
        fabric.Image.fromURL(data, function(img) {
            var oImg = img.set({ left: 50, top: 100, angle: 00 }).scale(0.9);
            canvas.add(oImg).renderAll();
            canvas.setActiveObject(oImg);
        });
    };
    reader.readAsDataURL(file);
});
&#13;
<script src="https://rawgit.com/kangax/fabric.js/master/dist/fabric.min.js"></script>
<canvas id="canvas"></canvas>
<input type="file" id="file">
&#13;
&#13;
&#13;

答案 1 :(得分:0)

这里有一个工作示例:http://jsbin.com/wecupu/2/edit

HTML

<!DOCTYPE html>
<html>
<head>
  <script src="//cdnjs.cloudflare.com/ajax/libs/fabric.js/1.4.13/fabric.min.js"></script>
  <meta charset="utf-8">
  <title>JS Bin</title>
</head>
<body>
  <input id="file" type="file" accept="image/*">
  <canvas id="canvas" width="600" height="600"></canvas>
</body>
</html>

JS

var readFile = function(e) {
  var input = e.target;

  var reader = new FileReader();

  reader.onload = function(){
    var img = document.createElement('img');
    img.src = reader.result;

    var image = new fabric.Image(img);
    canvas.add(image);
  };

  reader.readAsDataURL(input.files[0]);
};

document.getElementById('file').addEventListener('change', readFile);

var canvas = new fabric.Canvas(document.getElementById('canvas'), {
  backgroundColor: '#c8c8c8'
});

您只需使用FileReader将图像文件读取为base64格式,并将fabric.Image添加到画布。

但是,文件大小有限制。它因浏览器而异:What is the size limit of a Base64 DataURL image?

答案 2 :(得分:0)

角度解决方案:

打字稿:

uploadImage(event) {
    if (event.target.files.length > 0) {
        const file = event.target.files[0];
        const reader = new FileReader();

        reader.onload = (e: any) => {
            const data = e.target.result;
            fabric.Image.fromURL(data, img => {
                this.canvas.add(img);
                this.canvas.centerObject(img);
            });
        };

        reader.readAsDataURL(file);
    }
}

HTML:

<button type="button" mat-raised-button (click)="fileInput.click()">Choose File</button>
<input hidden (change)="uploadImage($event)" #fileInput type="file" id="file">

答案 3 :(得分:-1)

为什么不在输入字段上使用更改处理程序?

如果您添加了ID

<input type="file" name="Image" id="Image">

然后您可以尝试

//assuming jquery
$("#Image").on("change", function(e) {
   //run your code here
});