Search code examples
html5-canvasfabricjsfabricjs2

Why fabric.Path on FabricJS is display different from svg file?


I want to display an path in Fabric.JS, in svg file:

<g>
  <path style="fill:none;stroke:#000000;stroke-miterlimit:10;" 
    d="M221.58-0.55 c17.5,31.22,4.77,57.16-8.14,88.46c-13.75,33.35,0.71,57.72,0.71,57.72"/>
</g>

And code in my Fabricjs

var Path_0_1 = new fabric.Path('M221.58-0.55   c17.5,31.22,4.77,57.16-8.14,88.46c-13.75,33.35,0.71,57.72,0.71,57.72', {
  fill: 'none',
  stroke: '#000000',
  strokeMiterLimit: 10,
  opacity: 1,
});

But result is not same:
enter image description here

Expected: Path in FabricJS display same as in SVG file.

Here is my code:

var canvasObject = document.getElementById("editorCanvas");
// set canvas equal size with div
$(canvasObject).width($("#canvasContainer").width());
$(canvasObject).height($("#canvasContainer").height());

var canvas = new fabric.Canvas('editorCanvas', {
  backgroundColor: 'white',
  selectionLineWidth: 2,
  width: $("#canvasContainer").width(),
  height: $("#canvasContainer").height()
});

var Path_0_1 = new fabric.Path('M221.58-0.55   c17.5,31.22,4.77,57.16-8.14,88.46c-13.75,33.35,0.71,57.72,0.71,57.72', {
  //				fill : 'none',
  stroke: '#000000',
  strokeMiterLimit: 10,
  opacity: 1,
});
canvas.add(Path_0_1);
canvas.moveTo(Path_0_1, 1);
setObjectCoords();
canvas.renderAll();

function setObjectCoords() {
  canvas.forEachObject(function(object) {
    object.setCoords();
  });
}
#canvasContainer {
  width: 100%;
  height: 100vh;
  background-color: gray;
}
<script src="https://code.jquery.com/jquery-3.3.1.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/fabric.js/2.4.3/fabric.js"></script>
  
<div id="canvasContainer">
  <canvas id="editorCanvas"></canvas>
</div>


And here is my svg file:
https://svgur.com/s/Bw6


Solution

  • Set fill value '' || null || 'transparent', so on ctx.fill() it wont fill anything to the object.

    DEMO

    var canvasObject = document.getElementById("editorCanvas");
    // set canvas equal size with div
    $(canvasObject).width($("#canvasContainer").width());
    $(canvasObject).height($("#canvasContainer").height());
    
    var canvas = new fabric.Canvas('editorCanvas', {
      selectionLineWidth: 2,
      width: $("#canvasContainer").width(),
      height: $("#canvasContainer").height()
    });
    
    var Path_0_1 = new fabric.Path('M221.58-0.55c17.5,31.22,4.77,57.16-8.14,88.46c-13.75,33.35,0.71,57.72,0.71,57.72', {
      fill : null,
      stroke: '#000000',
    });
    canvas.add(Path_0_1);
    #canvasContainer {
      width: 100%;
      height: 100vh;
    }
    <script src="https://code.jquery.com/jquery-3.3.1.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/fabric.js/2.4.3/fabric.js"></script>
      
    <div id="canvasContainer">
      <canvas id="editorCanvas"></canvas>
    </div>