Search code examples
javascriptfabricjs

When adding image to canvas from an upload field it is selected but hidden behind the canvas


The input variable in the function is the image send from and upload input file field.

    function readURLForSticker(input) {
TypeBelettering = "sticker";
  if (input.files && input.files[0]) {
    
    var imgs = new Image();
    imgs.onload = function () {
      originalImageHeightPX = this.height;
      originalImageWidthPX = this.width;
      imageHeightMM = originalImageHeightPX * 0.2645833333;
      imageWidthMM = originalImageWidthPX * 0.2645833333;


    };
    imgs.onerror = function () {
      alert("not a valid file: " + file.type);
    };
    urlLogo = _URL.createObjectURL(input.files[0]);  
    imgs.src = urlLogo;
    reader = new FileReader();

    reader.onload = function (e) {
      imgs.src = e.target.result;
      
      stickerImage = new fabric.Image(imgs);
      canvas.add(stickerImage);
      canvas.centerObject(stickerImage);
      canvas.setActiveObject(stickerImage);
      canvas.renderAll();
    }

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

This is what sent by the input

$("#upload-picture").change(function() {

  readURLForSticker(this);
        
});

The image works when you drag it a little bit but for dummy's it is not useabble.


Solution

  • The code you've provided appears to be incomplete so rather than try to create a working example out of it, here is a basic demo of how to add an image to a Fabric.js canvas using a file input.

    var canvas = new fabric.Canvas('canvas');
    
    document.getElementById("uploader").onchange = function(e) {
      var reader = new FileReader();
      reader.onload = function(e) {
        var image = new Image();
        image.src = e.target.result;
        image.onload = function() {
          var img = new fabric.Image(image);
          img.set({
            left: 100,
            top: 100
          });
          img.scaleToWidth(200);
          canvas.add(img).setActiveObject(img).renderAll();
        }
      }
      reader.readAsDataURL(e.target.files[0]);
    }
    <script src="https://cdnjs.cloudflare.com/ajax/libs/fabric.js/4.5.0/fabric.min.js"></script>
    <canvas id="canvas" width="400" height="300" style="border:1px solid black"></canvas>
    <input id="uploader" type="file"/>