Search code examples
javascriptdom-eventsfabricjs

Fabricjs - select object programatically for immediate movement/drag


I am able to select object programatically using fabricjs. However, it does not behave like when one selects an object using mouse click. On a mouse click, the object comes under focus, and one can, for example, drag it. However, on programatic selection, I cannot immediately move an object. An example jsfiddle:

http://jsfiddle.net/ThzXM/1/

Programmatic selection:

canvas.setActiveObject(canvas.item(0));

What I would like to ultimately achieve is this: on clicking a button, a new rectangle is added to canvas, which the user can move around before placing it on canvas - without requiring extra clicks. Is it possible to do this in a cross-browser compatible way? (I know in some browsers I can fire a mouseclick event but most disallow it.)


Solution

  • You have to do this. Don´t forget to call setCoords() to update the bounding box of your object.

    // Set the active element
    canvas.setActiveObject(canvas.item(0));
    // Set left, o right,or angle... check documentation.
    //Don´t forget to call setCoords() after changes.
    canvas.item(0).setLeft(80).setCoords(); 
    //Then render the canvas
    canvas.renderAll()