bramchi
bramchi

Reputation: 810

Resize a fabricjs rect to maintain border size

I would like to resize a fabricjs rect instead of scale it, but I'm seeing weird behaviour while dragging the resize handles. The border starts to disappear or duplicate. I've tried both the stable version 1.7.19 and the beta 2.0.0 of fabricjs.

Here is the essence of the code I'm using:

canvas.on('object:scaling', function(){
    var obj = canvas.getActiveObject(),
        width = obj.width,
        height = obj.height,
        scaleX = obj.scaleX,
        scaleY = obj.scaleY;

    obj.set({
        width : width * scaleX,
        height : height * scaleY,
        scaleX: 1,
        scaleY: 1
    });
});

Working example here: https://codepen.io/bramchi/pen/GMLYEV/

Try scaling it up and down a bit by dragging the resize handles.

Screenshot of scaling up and down issues

What I would expect to happen is the rectangle growing and shrinking while dragging the handles, and the border size to stay the same. But somehow rendering starts to go bonkers if you cross 270px or so. When the mouse button is released, it renders properly again.

What am I doing wrong? Who knows a fix? Or could this be a bug in the library I can report?

Upvotes: 2

Views: 3631

Answers (2)

AndreaBogazzi
AndreaBogazzi

Reputation: 14741

as described here:

http://fabricjs.com/fabric-object-caching ( really last line )

disabling noScaleCache is enough. That gives you caching anyway, just it invalidates cache everytime you scale the object.

Not that caching a rect is that usefull, but if you have the same behaviour for complex paths, that is still a good thing to have.

  new fabric.Rect({
    left: 50,
    top: 50,
    width: 250,
    height: 250,
    stroke: 'gray',
    fill: 'lightgray',
    strokeWidth: 10,
    noScaleCache: false,
  })

Upvotes: 1

bramchi
bramchi

Reputation: 810

Disable object caching to avoid this rendering behaviour:

fabric.Object.prototype.objectCaching = false;

For performance reasons Fabric.js caches objects by default during drag rotate skew and scale operations. One of the moderators of the fabric.js repo pointed me in the right direction, hooray for him!

Upvotes: 1

Related Questions