【问题标题】:How to prevent canvas object movement X-axis left direction only (FabricJS)如何防止画布对象仅在 X 轴左方向移动(FabricJS)
【发布时间】:2015-10-12 01:38:57
【问题描述】:

我正在尝试将画布对象绑定在织物画布中。通常当创建对象时,它可以移动到画布外部,如下所示:

但我只想在画布内移动它。它不能在外面。这是我的代码:

  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();

我已经看到了canvas.item(0).lockMovementX = true;这个选项,但我认为它不能解决我的问题。

【问题讨论】:

    标签: javascript html canvas fabricjs


    【解决方案1】:

    这个有很多解决方案:

    JS部分:

    $(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);
    });
    

    看看这个JsFiddle

    【讨论】:

      猜你喜欢
      • 2021-05-20
      • 1970-01-01
      • 2019-04-08
      • 1970-01-01
      • 1970-01-01
      • 2015-07-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多