Byrd
Byrd

Reputation: 37

fabricjs limiting object drag

Referring to the code below, I can drag the red line back and forth within the canvas box and have it stop at the left limit. But the line doesn't stop at the right limit - it disappears beyond the box and reappears if I drag left. I have looked at fabricjs demos (Standalone Controls, PerPixel Drag and Drop, Stickman) and notice that it is possible to drag objects "out of sight" in a similar manner. Is this a characteristic of fabricjs, or is there some way I can fix my code so that the red line cannot be dragged beyond the right limit?

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

var leftLimit = 20;
var rightLimit = 400;


var redLine = new fabric.Line([leftLimit, 0, leftLimit, canvas.height], {
  stroke: 'red',
  strokeWidth: 2,
  borderColor: 'white',
  hasControls: false
});

canvas.add(redLine);
canvas.renderAll();

canvas.on('object:moving', function(e) {
  redLine = e.target;
  redLine.set({
    top: 0
  });

  if (redLine.left < leftLimit) {
    redLine.set({
      left: leftLimit
    });
  }

  if (redLine > rightLimit) {
    redLine.set({
      left: rightLimit
    });
  }

  canvas.renderAll();

});
<script src="https://cdnjs.cloudflare.com/ajax/libs/fabric.js/2.4.3/fabric.js"></script>
<canvas id="cnvs" width="500" height="200" style="border:1px solid #000000"></canvas>

Upvotes: 0

Views: 893

Answers (1)

shkaper
shkaper

Reputation: 4998

I'm not sure if you made a typo or not, but (redLine > rightLimit) makes no sense. You should compare left:

  if (redLine.left > rightLimit) {
    redLine.set({ left: rightLimit });
  }

Or, since your line has some width to it, you can make it stop without ever overlapping the boundary:

  if (redLine.left + redLine.strokeWidth > rightLimit) {
    redLine.set({ left: rightLimit - redLine.strokeWidth });
  }

Upvotes: 1

Related Questions