Andre Helberg
Andre Helberg

Reputation: 551

Why do lines and rects not match up in Fabricjs

Why does the following rect and lines not match up? off-center rect

The lines are 1px apart, 5px long, starting from (0,0)

The rect is top: 0, left: 0, width: 1, height: 1

Running fiddle

Am I missing something with lines?

Upvotes: 0

Views: 229

Answers (3)

Durga
Durga

Reputation: 15604

The padding you got because of strokeWidth of the Rect object, make it zero, it will work as expected. jsfiddle

DEMO

var canvas = new fabric.Canvas('c');

var gridLine = function(at, stroke, canvas, length) {
  var horizontal = [0, at, length, at];
  var vertical = [at, 0, at, length];

  let hLine = new fabric.Line(horizontal, {
    strokeWidth: 0.02,
    stroke,
  });
  let vLine = new fabric.Line(vertical, {
    strokeWidth: 0.02,
    stroke,
  });
  canvas.add(hLine);
  canvas.add(vLine);
}

var showGrid = function(fabric) {
  var count = 5;
  var separationPx = 1;
  for (var i = 0; i < count; i++) {
    gridLine(i * separationPx, "silver", fabric, count);
  }
}

var rect = new fabric.Rect({
  top: 0,
  left: 0,
  width: 1,
  height: 1,
  fill: "red",
  strokeWidth: 0
});

showGrid(canvas);
canvas.add(rect);

canvas.setZoom(50);
<script src="http://cdnjs.cloudflare.com/ajax/libs/fabric.js/2.3.4/fabric.js"></script>
<canvas id="c" width="300" height="300"></canvas>

Upvotes: 1

Tobias O.
Tobias O.

Reputation: 1

I am a beginner to Fabricjs so there might be an easier answer. To me it looks like the "padding" (?) is what causes the problem. Look at the control borders when you select the rectangle, they do align but are bigger than your rectangle is.

I could fix this by setting the rect to (-0.5, -0.5, 1, 1), however I think this is not the best workaround and you should probably try to adjust the padding of your rect.

Hope it helps in a way.

Cheers!

Edit: It's not the padding it's the strokeWidth as Durga pointed out in the comments to the question.

Upvotes: 0

user10608712
user10608712

Reputation:

There is no problem:

[http://jsfiddle.net/odwg3nsq/]

enter image description here

You could set the padding/margin of the outer container, but in the canvas everything is ok with the rectangle.

Upvotes: 0

Related Questions