Search code examples
javascripthtml5-canvasfabricjs

Fabric.JS and Fabric-Brush - Can't add to lower canvas


I'm trying to use Fabric.js with Fabric Brush This issue that I'm running into is that Fabric Brush only puts the brush strokes onto the Top Canvas and not the lower canvas. (The stock brushes in fabric.js save to the bottom canvas) I think I need to convert "this.canvas.contextTop.canvas" to an object and add that object to the the lower canvas. Any ideas?

I've tried running:

this.canvas.add(this.canvas.contextTop)

in

  onMouseUp: function (pointer) {this.canvas.add(this.canvas.contextTop)}

But I'm getting the error

Uncaught TypeError: obj._set is not a function

Solution

  • So the contextTop is CanvasHTMLElement context. You cannot add it. You can add to the fabricJS canvas just fabric.Object derived classes.

    Look like is not possible for now. They draw as pixel effect and then they allow you to export as an image. Would be nice to extend fabricJS brush interface to create redrawable objects.

    As of now with fabricJS and that particular version of fabric brush, the only thing you can do is:

    var canvas = new fabric.Canvas(document.getElementById('c'))
    
    canvas.freeDrawingBrush = new fabric.CrayonBrush(canvas, {
      width: 70,
      opacity: 0.6,
      color: "#ff0000"
    });
    
    canvas.isDrawingMode = true
    
    canvas.on('mouse:up', function(opt) {
      if (canvas.isDrawingMode) {
        var c = fabric.util.copyCanvasElement(canvas.upperCanvasEl);
        var img = new fabric.Image(c);
        canvas.contextTopDirty = true;
        canvas.add(img);
        canvas.isDrawingMode = false;
      }
    })
    <script src="https://cdnjs.cloudflare.com/ajax/libs/fabric.js/2.4.1/fabric.min.js"></script>
    <script src="https://tennisonchan.github.io/fabric-brush/bower_components/fabric-brush/dist/fabric-brush.min.js"></script>
    <button>Enter free drawing</button>
    <canvas id="c" width="500" height="500" ></canvas>

    That is just creating an image from the contextTop and add as an object.