Update fabric.js Path points dynamically

前端 未结 4 787
栀梦
栀梦 2021-01-20 04:05

I\'m trying to add points to a path object dynamically. When I do, the path renders correctly, but the bounding rectangle never gets updated, making it nearly impossible for

4条回答
  •  再見小時候
    2021-01-20 04:56

    It ended up being more complicated. If a point is added to the path that results in _parseDimensions returning a left value that is negative, the path would jump around the screen. For my use case, I need the path to stay in place while points are added and manipulated. This fiddle shows my working solution:

    http://jsfiddle.net/flyingL123/8763bx2q/8/

    If you run it with a JS console open, you will see the script pausing after each additional point is added, or current point is manipulated. As this happens you will see that the path does not get moved along the canvas, which is the desired behavior. After all the break points complete, you will see that the curve is centered within its selection box.

    If there is an easier way to achieve this behavior, I would love to know.

    Here's the function I'm using to set the dimensions just in case the fiddle link ever goes away:

    function updateDims() {
        var dims = path._parseDimensions(),
            prevDims = path.prevDims || {},
            leftDiff = dims.left - (prevDims.left || 0),
            topDiff = dims.top - (prevDims.top || 0);
    
        path.setWidth(dims.width);
        path.setHeight(dims.height);
    
        if (dims.left < 0) {
            path.pathOffset.x = path.width/2 + dims.left;
            path.left = path.left + leftDiff;
        } else {
            path.pathOffset.x = path.width/2;
        }
    
        if (dims.top < 0) {
            path.pathOffset.y = path.height/2 + dims.top;
            path.top = path.top + topDiff;
        } else {
             path.pathOffset.y = path.height/2;   
        }
    
        path.prevDims = dims;
        path.setCoords();
    }
    

提交回复
热议问题