0

I am using FabricJS to draw and erase lines on top of an image. I made 2 layers for the canvas, with the bottom layer as the background image and the top layer for sketching. Whenever I erase the markings, if I use freeDrawingBrush.color =white, or any basic color, it gets erased. However, if I use transparent, 'rgba(0,0,0,0)', as the color of the freeDrawingBrush, the markings are not erased.

How can I erase the marking on the top layer with a transparent as the background of the path created as I erase?

<div style="position: relative;">
    <canvas id="my-canvas" width="800" height="400" style="position: absolute; left: 0; top: 0; z-index: 1;background-color:rgba(0,0,0,0)"> </canvas> 
    <canvas id="layer3" width="800" height="400" style="position: absolute; left: 0; top: 0; z-index: 0;background-image:url(http://gallery.nanfa.org/d/52271-3/DSC_7537.jpg);"></canvas>
</div>

<script>
 canvas = window._canvas = new fabric.Canvas('layer1');
 canvas.isDrawingMode= 1;
 canvas.freeDrawingBrush.width = 10;
 canvas.renderAll();

//eraser function
 function eraser(){
  canvas.freeDrawingBrush.color = "white"; // if "rgba(0,0,0,0)", not work
  canvas.on('path:created', function (opt) {
      opt.path.globalCompositeOperation = 'destination-out';
      canvas.renderAll();
  });
}

//drawing function
function draw(){
    canvas.freeDrawingBrush.color = "black";
    canvas.on('path:created', function (opt) {
        opt.path.globalCompositeOperation = 'source-over';
        canvas.renderAll();
    });
}

</script>

Im using fabricjs on html https://cdnjs.cloudflare.com/ajax/libs/fabric.js/1.7.22/fabric.min.js

Any help will be very much appreciated. Thanks in advance!

Marci Banez
  • 115
  • 1
  • 9
  • See here for tips on building an eraser - https://stackoverflow.com/questions/19311038/fabric-js-eraser-issue-canvas – melchiar May 14 '19 at 03:04
  • I checked that out, however, the eraser function cannot have a transparent background, it needs to have solid color such as white or black in order to work. I need a transparent background for the path created when erasing lines.. – Marci Banez May 14 '19 at 06:22
  • Unfortunately you can't draw using transparency since you'd essentially be drawing with nothing (think of it like drawing on top of paint with invisible ink). Fabric.js is object rather than pixel based so your best approach would be to either create a clippath from your drawn path or use a globalcompositeoperation, both of which you should be able to find several other examples of. – melchiar May 14 '19 at 13:58
  • 1
    could you provide some links on that? especially on the clippath creation? I tried researching about the globalcompositeoperation, and had no luck.. I wanted the functionality of the regular HTML canvas, but the sketches cannot be saved, loaded and edited again so I used FabricJS. Everything is working fine, except that transparent eraser function.. Thanks in advance! – Marci Banez May 15 '19 at 07:12

0 Answers0