【问题标题】:How to detect center line of a canvas to center a object when it dragged?拖动时如何检测画布的中心线以使对象居中?
【发布时间】:2016-08-22 15:48:43
【问题描述】:

这个问题属于fabricJS和canvas。当我将一个对象拖到canvas上时,我需要检测中心线并捕捉到它。我在this question 中发现了一些类似的方法。但它处理div 元素。我需要处理画布的中心线。我该怎么做?

【问题讨论】:

    标签: javascript jquery html canvas fabricjs


    【解决方案1】:

    Canvas 或 Fabric.Rect 的中心点

    如果你有一个这样定义的矩形:

    var rect = {x:0, y:0, width:50, height:30};
    

    你可以这样计算矩形的中心点:

    var centerX = x+width/2;
    var centerY = y+height/2;
    

    两点之间的中点(== 线段的中点)

    如果你有这样定义的线段:

    var line={ x0:0, y0:50, x1:100, y1:50 }
    

    你可以这样计算线段的中点:

    var dx = x1-x0;
    var dy = y1-y0
    var midX = x0 + dx*0.50;
    var midY = y0 + dy*0.50;
    

    【讨论】:

      【解决方案2】:

      您可以使用moving 选项手动定义快照功能。尝试跟随。

          'object:moving' : function(e){
          var objCenter = e.target.getLeft() + (e.target.getWidth()/2);
      
      
          var targetLine = canvas.left+(canvas.width/2); 
      
      
          if(objCenter > targetLine-10 && objCenter < targetLine+10){
      
              e.target.left = targetLine - (e.target.getWidth()/2) ;
          }else{
              e.target.setOpacity(1);
          }  
      

      `

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2017-12-22
        • 1970-01-01
        • 2016-04-18
        • 1970-01-01
        • 2018-10-29
        • 2013-08-04
        • 1970-01-01
        相关资源
        最近更新 更多