Is there a way to import an image file using fabri

2019-06-05 22:41发布

问题:

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

回答1:

Yes!

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>