fabricjsfabricjs2

fabricjs2 selection error after programmatically resize


I'm using fabrics v2.4.3 in an angular 6 project. In my project I want to move and resize some objects (a fabric.Group) both by mouse and by properties editing through a form.

The problem is on the second method.

I put an object into the canvas, and I selected it by mouse. Now I'm subscribed to the form valueChanges to apply in real time the new props of the selected object.

this.subscription = this.form.valueChanges.subscribe((value)=>{
  this.panelView.setConfig(value);  
})

This is the setConfig method:

setConfig(config:PanelParameters){
    this.config = config;
    let param = {            
        top: this.config.y,
        left: this.config.x,

        width: this.view.width, //this.config.width,
        height: this.view.height,

        scaleX: this.config.width/this.view.width,
        scaleY: this.config.height/this.view.height,
        fill : this.config.background_color

    }
    this.view.set(param)

    for(let obj of this.view.getObjects()){
        if(  obj instanceof fabric.Rect){
            obj.set({
                fill: this.config.background_color
            })
        }else if( obj instanceof fabric.Text ){
            obj.set({
                fill: this.config.title_text_color
            })
        }
    }

    this.canvas.requestRenderAll();
}

Now into the canvas the object are rendered correctly but if I try to select it I have to click onto the old object area.

What I'm doing wrong?


Solution

  • You're missing a call to this.view.setCoords().

    In fabric.js, mouse interactions are evaluated against an object's oCoords. When you programmatically set object's properties that should result in a change of coordinates, you have to explicitly call setCoords() to recalculate them. See When to call setCoords.