Search code examples
javascripthtml5-canvasfabricjs

Draw New Path beneath Overlay Image


When I draw a new path in fabric.js isDrawingMode: true (right side of the screenshot) I want it to appear beneath my overlay image, that is a transparent png.

enter image description here

        var canvas = this.__canvas = new fabric.Canvas('c', {
            isDrawingMode: true,
            preserveObjectStacking: true
        });


        var img = fabric.Image.fromURL(imgUrl, function(oImg) {
            oImg.scaleToWidth(canvas.getWidth());
            oImg.id="OverlayImage";
            canvas.setOverlayImage(oImg, canvas.renderAll.bind(canvas));
        });

It works as soon as I finish the path, though.

I experimented with multiply filter, and stacking order on mouse move event, but got nowhere.

Any idea how to solve this!

https://codepen.io/localhorst/pen/zYvKWqo


Solution

  • a 100% fabric solution would imply not to use the fabric brush/freeDrawingMod. you could create your draw path and add it to the canvas as a fabric object by tracking mousedown and mousemove, updating your fabric path object each mousmove. There is a nice explanation for creating a path object at the end of the page : http://fabricjs.com/fabric-intro-part-1

    Simpler solution would be to set the image as a html element positioned on top of the canvas. with pointer-events disabled on the image you could click through and draw on the fabric canvas.

    from your codepen:

    <div class="row">
        <img class="overlay" src="https://sandmoshi.github.io/eColorBook/pages/fox-trans.png"/>
        <div class="col-8">
                <canvas id="c" height="600" width="800" style="border:1px solid #aaa;"></canvas>
            </div>
    ...
    
    .overlay{
      position:absolute;
      top: 0;
      left: 0;
      z-index: 1000;
      -webkit-user-drag: none;
      -khtml-user-drag: none;
      -moz-user-drag: none;
      -o-user-drag: none;
      user-drag: none;
      pointer-events: none;
    }
    

    i have forked your pen to demonstrate : https://codepen.io/TheNils/pen/QWjdEOR