简体   繁体   中英

How to prevent canvas object movement X-axis left direction only (FabricJS)

what i am trying is to bound the canvas object in fabric canvas .Normally when an obejct is created it can be moved to outside of the canvas like below: 画布文字移到外面

But i want to move it only inside the canvas.It can't be outside. Here is my code:

  var canvas = new fabric.Canvas('c');
  var SampleText = new fabric.Text(Text, {
    left: canvas.getWidth() / 2,
    top: canvas.getHeight() / 2       
  });
  SampleText.on('moving', function(e) {     
       // need to immplement the logic here
    });
  canvas.add(SampleText);
  canvas.renderAll();

I already have seen the option canvas.item(0).lockMovementX = true; But I think it will not solve my problem.

Well there are many solutions for this :

JS Part :

$(document).ready(function() {
    var canvas=new fabric.Canvas('demo');
    canvas.on('object:moving', function (e) {
        var obj = e.target;
         // if object is too big ignore
        if(obj.currentHeight > obj.canvas.height || obj.currentWidth > obj.canvas.width){
            return;
        }        
        obj.setCoords();        
        // top-left  corner
        if(obj.getBoundingRect().top < 0 || obj.getBoundingRect().left < 0){
            obj.top = Math.max(obj.top, obj.top-obj.getBoundingRect().top);
            obj.left = Math.max(obj.left, obj.left-obj.getBoundingRect().left);
        }
        // bot-right corner
        if(obj.getBoundingRect().top+obj.getBoundingRect().height  > obj.canvas.height || obj.getBoundingRect().left+obj.getBoundingRect().width  > obj.canvas.width){
            obj.top = Math.min(obj.top, obj.canvas.height-obj.getBoundingRect().height+obj.top-obj.getBoundingRect().top);
            obj.left = Math.min(obj.left, obj.canvas.width-obj.getBoundingRect().width+obj.left-obj.getBoundingRect().left);
        }
    });
    var text=new fabric.IText('Jayesh');
    canvas.add(text);
});

Have a look at this JsFiddle

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM