Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Update fabric.js Path points dynamically

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 a user to select and move the path on canvas.

As you can see in the code below, the path is initially created with a single point, then I dynamically add a second point as well as a control point. After doing this, the bounding rectangle never updates:

var canvas = new fabric.Canvas('c');
canvas.backgroundColor = '#f5f5f5';
var path = new fabric.Path('M 0 20',{
    left: 100,
    top: 100,
    stroke: 'black',
    fill: ''
});

canvas.add(path);

var commandArray = [];
commandArray[0] = 'Q';
commandArray[1] = 50;
commandArray[2] = 100;
commandArray[3] = 100;
commandArray[4] = 20;

path.path[1] = commandArray;

canvas.renderAll();

I also tried calling path.setCoords(), but that did not make any difference. How can I get the bounding rectangle to update its dimensions after adding points to a path?

Here's a fiddle: http://jsfiddle.net/flyingL123/17ueLva2/2/

like image 839
flyingL123 Avatar asked Dec 11 '22 00:12

flyingL123


2 Answers

In fabric 3.3.2 I solved it combining the answers above:

var dims = path._calcDimensions()
path.set({
  width: dims.width,
  height: dims.height,
  left: dims.left,
  top: dims.top,
  pathOffset: {
    x: dims.width / 2 + dims.left,
    y: dims.height / 2 + dims.top
  },
  dirty: true
})
path.setCoords()

This correctly updates my path bounding box after adding points like:

path.set({path: points})

I am not sure though, if this works with negative top and left values, but I didn't need that in my case. I guess the main thing is that the _parseDimensions() method was renamed to _calcDimensions().

like image 113
ezpzlmnsqz1337 Avatar answered Dec 13 '22 13:12

ezpzlmnsqz1337


Please, fabricjs does not support adding point dinamically as of now. To make it work you can add points like you are doing and then use internal method path._parseDimensions() each time you add points and desire to update bounding box dimension.

var dims = path._parseDimensions();
path.setWidth(dims.width);
path.setHeight(dims.height);
path.pathOffset.x = path.width/2;
path.pathOffset.y = path.height/2;
path.setCoords();

Look this updated fiddle that has the necessary code to solve your problem. I hope it works for every situation.

http://jsfiddle.net/17ueLva2/6/

like image 33
AndreaBogazzi Avatar answered Dec 13 '22 12:12

AndreaBogazzi