Search code examples
fabricjs

Render static object in foreground / object invisible to mouse events


I am trying to render a frame always in forefront for the purpose of a kind of static clipping to predefined size. You can move objects around and the frame indicates to what area your canvas will be clipped when you hit save.

There is no foreground functionality so the way I went about this is to render rectangle with transparent fill and a single pixel wide stroke:

var out_frame = new fabric.Rect({
    width: OUTPUT_WIDTH + 2,
    height: OUTPUT_HEIGHT + 2,
    fill: 'rgba(0, 0, 0, 0)',
    selectable: false,
    stroke: 'rgba(0,255,0,1)',
    strokeWidth: 1
});

and made sure it stays in front of other objects:

canvas.on('object:added', function(e) {
    out_frame.bringToFront();
});

Here's the problem: even though the frame object cannot be selected and is transparent it obstructs objects beneath it from being manipulated with mouse. You cannot for example select object beneath frame with single click. When you try this the frame object doesn't get selected - it's not selectable but neither does the object beneath.

Any suggestions how to fix this or perhaps how to go about this some other way entirely?


Solution

  • use the property evented set to false the rectangle will be then "dead". it will be drawn and nothing else will happen with it.

    var canvas = new fabric.Canvas('canvas');
    var out_frame = new fabric.Rect({
    width: 300 + 2,
    height: 300 + 2,
    fill: 'rgba(0, 0, 0, 0)',
    selectable: false,
    stroke: 'rgba(0,255,0,1)',
    strokeWidth: 1,
    evented: false
    });
    
    canvas.add(out_frame);
    
    canvas.on('object:added', function(e) {
    out_frame.bringToFront();
    });
    
    canvas.add(new fabric.Circle({radius: 20, fill:'blue'}));
    <script src="http://cdnjs.cloudflare.com/ajax/libs/fabric.js/1.5.0/fabric.min.js" ></script>
        <canvas id="canvas" width=500 height=200 style="height:500px;width:500px;"></canvas>