Add image from user computer to canvas

前端 未结 2 992
独厮守ぢ
独厮守ぢ 2020-12-06 12:06

i\'m working on a web app that allow users to create dynamic slideshow. Currently i\'ve got an issue regardless how to add image from the computer\'s user to the canvas. I\'

相关标签:
2条回答
  • 2020-12-06 12:43

    There is one basic mistake in your code, you are trying to add the image data to the src attribute of the fabric.Image object.

    What you need to do, is to create an Image object with your result, and pass it to the fabric.Image object, like this:

    var imgObj = new Image();
    imgObj.src = event.target.result;
    imgObj.onload = function () {
      var image = new fabric.Image(imgObj);
    }
    

    I made a working example here: http://jsfiddle.net/jaibuu/Vp6wa/

    0 讨论(0)
  • 2020-12-06 12:48

    Upload image in canvas from computer by Fabric js.

    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: 0, top: 0, angle: 00,width:100, height:100}).scale(0.9);
          canvas.add(oImg).renderAll();
          var a = canvas.setActiveObject(oImg);
          var dataURL = canvas.toDataURL({format: 'png', quality: 0.8});
        });
      };
      reader.readAsDataURL(file);
    });
    canvas{
      border: 1px solid black;
    }
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <script src="https://rawgit.com/kangax/fabric.js/master/dist/fabric.min.js"></script>
    <input type="file" id="file"><br />
    <canvas id="canvas" width="450" height="450"></canvas>

    0 讨论(0)
提交回复
热议问题