0

I'm trying to create a simple path object using Farbic.js. When the path is added to canvas, it does not appear to be positioned correctly. Here is my code:

HTML

<canvas id="c" height="300" width="300"></canvas>

JS

var canvas = new fabric.Canvas('c');
canvas.backgroundColor = '#f5f5f5';
var line = new fabric.Path('M 0 0 L 100 100',{
    stroke: 'black',
    fill: ''
});
canvas.add(line);

According to the data I'm passing in, the path should start at point 0,0 and draw a line to point 100, 100. However, my line is actually being placed at point 50,50, as you can see by the alert.

Why isn't the path starting at point 0,0?

Here's a fiddle: http://jsfiddle.net/flyingL123/h14th5pf/3/

Aweary
  • 2,302
  • 17
  • 26
flyingL123
  • 7,686
  • 11
  • 66
  • 135

1 Answers1

1

You can specify the position properties of your path explicitly.

line.set({top: 0, left: 0});

Fabric.JS seems to include some sort of computed padding by default, based on the line length and canvas size. Try adjusting your canvas dimensions and line length and you'll see the top and left values update automatically.

Edit: It appears Fabric.JS may use the center of the canvas to calculate the X,Y positions for canvases. It may use a similar scheme for path origin points. See this related StackOverflow question:

Canvas coordinates in Fabric.js have offset

It seems to be part of how the library calculates positions automatically. Per the comments of the linked question, you can fix this with:

fabric.Object.prototype.originX = true; 
fabric.Object.prototype.originY = true;

And you wont have to adjust the originX or originY properties on each path object.

Community
  • 1
  • 1
Aweary
  • 2,302
  • 17
  • 26
  • It seems strange that it doesn't get positioned to the starting point. If the path goes from left to right, it's simple to add an extra line to set the position like you show above. But, if the path goes right to left, I would first have to change the path's `originX` to `right`, and then position. This seems less than ideal. – flyingL123 Feb 20 '15 at 21:41
  • Check out my edit and the link to the other SO question. It appears the library may be calculating the `x` and `y` positions a bit strangely. – Aweary Feb 20 '15 at 21:50