有没有办法使用fabric.js导入图像文件? [英] Is there a way to import an image file using fabric.js?

查看:259
本文介绍了有没有办法使用fabric.js导入图像文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前正在使用fabric.js库和输入文件按钮将png或svg文件导入画布。以下代码仅在图像位于根文件夹中时才有效。我知道我无法访问文件路径,因此我尝试从文件中创建一个元素。控制台中没有错误,但画布中没有显示任何内容。有没有办法让输入工作或是否有一个不同的库可以帮助我这样做?我正在使用fabric.js,以便能够在画布中缩放和移动图像。

I am currently working on importing png or svg files onto a canvas using the fabric.js library and an input file button. The code below works only if the image is in the root folder. I know that I don't have access to the file path, so I tried creating an element out of the file. There is no error in the console but nothing shows in the canvas. Is there a way to do make the importation work or is there a different library that could help me do this? I am using fabric.js in order to be able to scale and move the images within the canvas.

function upload(){
    var canvas = new fabric.Canvas('canvas');
    var file = document.getElementById('file').files[0].name;
    fabric.Image.fromURL(file, function(img) {
        canvas.add(img);
    })
}


推荐答案

是的!

有一种方法可以使用FabricJS导入image / svg文件,如下所示......

There is a way to import an image / svg file using FabricJS, and that is as follows ...

var canvas = new fabric.Canvas('c');

function upload(e) {
   var fileType = e.target.files[0].type;
   var url = URL.createObjectURL(e.target.files[0]);

   if (fileType === 'image/png') { //check if png
      fabric.Image.fromURL(url, function(img) {
         img.set({
            width: 180,
            height: 180
         });
         canvas.add(img);
      });
   } else if (fileType === 'image/svg+xml') { //check if svg
      fabric.loadSVGFromURL(url, function(objects, options) {
         var svg = fabric.util.groupSVGElements(objects, options);
         svg.scaleToWidth(180);
         svg.scaleToHeight(180);
         canvas.add(svg);
      });
   }
}

canvas {
   margin-top: 5px;
   border: 1px solid #ccc
}

<script src="https://cdnjs.cloudflare.com/ajax/libs/fabric.js/1.7.13/fabric.min.js"></script>
<input type="file" onchange="upload(event)">
<canvas id="c" width="180" height="180"></canvas>

这篇关于有没有办法使用fabric.js导入图像文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆