Don Rhummy
Don Rhummy

Reputation: 25900

How do I select and drag a different object than the one clicked in fabricjs?

I draw multiple objects on a canvas, but the top one has transparency. So you can see images behind it. It is unselectable. I want to be able to click on that image and then programatically select an image behind it and when I drag the mouse, move that one (not the front, trasnparent image).

I tried this code but it doesn't work:

function onSelect(event)
{
    var activeObject = canvas.getActiveObject();
    var newActive = canvas.getObjects()[ 0 ];

    //Do nothing
    if ( activeObject === newActive ) return;

    //Switch
    canvas.setActiveObject( newActive );
}

//Add listener
canvas.on( "object:selected", onSelect );

This appears to select the right object, but it won't drag it.

Upvotes: 1

Views: 830

Answers (1)

StefanHayden
StefanHayden

Reputation: 3669

have you tried just setting the selectable and evented property to false? here is an example with a blue square over two other squares. you can only interact with the 2 objects below the blue square and not the blue square at all.

var canvas = new fabric.Canvas("c", { preserveObjectStacking: true });

canvas
  .add(new fabric.Rect({
    top: 0,
    left: 0,
    width: 100,
    height: 100,
    fill: "green"
  }))
  .add(new fabric.Rect({
    top: 50,
    left: 50,
    width: 100,
    height: 100,
    fill: "red"
  }))
  .add(new fabric.Rect({
    top: 0,
    left: 0,
    width: 400,
    height: 300,
    opacity: 0.5,
    fill: "blue",
    selectable: false,
    evented: false,
  }))
  .renderAll();
canvas { border: 1px solid black; }
<canvas id="c" width="400" height="300"></canvas>
<script src="https://cdnjs.cloudflare.com/ajax/libs/fabric.js/1.6.3/fabric.min.js"></script>

Upvotes: 1

Related Questions