Resize a fabricjs rect to maintain border size

霸气de小男生 提交于 2019-12-10 10:44:29

问题


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?


回答1:


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!




回答2:


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,
  })


来源:https://stackoverflow.com/questions/46878814/resize-a-fabricjs-rect-to-maintain-border-size

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!