Search code examples
canvasmouseeventfabricjsmouseout

fabricjs: How to make the canvas object (rectangle) always active on mouse:down event also?


How to make the selection of canvas object ( rectangle) always active even after mouse:down event ? I have tried with the subTargetCheck:true property; but this property is not fulfilling the said requirement.

this.fabricObject = new fabric.Rect({
  left: this.objectSize.left,
  top: this.objectSize.top,
  width: this.objectSize.width,
  height: this.objectSize.height,
  fill: '#ccc',
  padding: 10,
  subTargetCheck: true
});

this.canvas.add(this.fabricObject);
this.fabricObject.center().setCoords();
this.canvas.renderAll();

=> Code for set always active

this.canvas.on('mouse:down', (e) => {
  console.log(e.target)
  this.canvas.getObjects().map((object:any) => {
    object.set('active', true);
    this.canvas.renderAll();
  })
});

=> If i do it for color fill then it is working fine on mouse out event.

this.canvas.on('mouse:down', (e) => {
  console.log(e.target)
  this.canvas.getObjects().map((object:any) => {
    object.set('fill', 'green');
    this.canvas.renderAll();
  })
});

REF: https://jsfiddle.net/jasie/r3fqu4p6/12/

As in the jsfiddle when click on the square it is going to active and when click out side of square it is going to deactivate... so i want that active too while clicking outside of that square.


Solution

  • You need to use canvas.setActiveObject() to manually set an active object on the canvas.

    var canvas = new fabric.Canvas("canvas");
    var ourRect = new fabric.Rect({
        left: 100,
        top: 100,
        width: 75,
        height: 50,
        fill: "green",
        padding: 10,
        subTargetCheck: true
    });
    
    canvas.add(ourRect);
    
    canvas.on("mouse:down", object => {
        canvas.setActiveObject(ourRect);
    });
    

    Please check this CodeSansbox demo: https://codesandbox.io/s/stackoverflow-60522500-fabric-js-1720-ekocp