2

I use fabricJS to edit an image, i've already implemented a zoom tool and a pan tool.

The paning method :

if (!this.isStartedAction) return;
                    var x = ev.e.screenX,
                        y = ev.e.screenY;
                    this.canvas.relativePan({ x: x - this.firstPositionPan.x, y: y - this.firstPositionPan.y });
                    this.firstPositionPan.x = x;
                    this.firstPositionPan.y = y;

Problem is, regardless if i zoomed or not, when i use the pan i can move my image outside the canvas. I would like to limit the move to the edge of the canvas but i don't know how to do.

Any suggestion?

Lempkin
  • 1,458
  • 2
  • 26
  • 49
  • Can you include some fiddle? Did you try absolutePan? Maybe your problem is in calculation x and y. Try to use x = Canvas.left, y = Canvas.top – Observer Jan 27 '17 at 13:45
  • 1
    Actually i found the solution myself, checking the viewportTransform[4] and [5] which must be <=0 and >=canvas.width, so when it's not, i force the value. Thx anyway =) – Lempkin Jan 27 '17 at 14:56
  • You can set on object modified listener and check if object is out of bounds. If so, then restore it to its original state. Check my answer [here](https://stackoverflow.com/a/42915768/2598453). – Milan Hlinák Jun 05 '17 at 20:37

1 Answers1

2

Try this

canvas.on('mouse:move', function (e) {
        if (isPanning && e && e.e) {
            var delta = new fabric.Point(e.e.movementX, e.e.movementY);
            canvas.relativePan(delta);

            var canvasViewPort = canvas.viewportTransform;

            var imageHeight = canvas.height * canvasViewPort[0];
            var imageWidth = canvas.width * canvasViewPort[0];

            var bottomEndPoint = canvas.height * (canvasViewPort[0] - 1);
            if(canvasViewPort[5] >= 0 || -bottomEndPoint > canvasViewPort[5]) {
                canvasViewPort[5] = (canvasViewPort[5] >= 0) ? 0 : -bottomEndPoint;
            }

            var rightEndPoint = canvas.width * (canvasViewPort[0] - 1);
            if(canvasViewPort[4] >= 0 || -rightEndPoint > canvasViewPort[4]) {
                canvasViewPort[4] = (canvasViewPort[4] >= 0) ? 0 : -rightEndPoint;
            }

        }
    });