Kineticjs dragBoundFunc for a rect in a rect

后端 未结 1 520
庸人自扰
庸人自扰 2020-12-20 00:50

i have following code to drag a smaller rect in a bigger rect.

it is almost working, but its possible to move the orange rect out of the white one. Is there any sol

1条回答
  •  难免孤独
    2020-12-20 01:03

    This is an improved way of setting your dragBoundFunc

    The secret with dragBoundFunc is to allow it to execute fast. Remember that it is being executed with every mousemove.

    So, pre-calculate all the minimum and maximum boundaries before and outside dragBoundFunc, like this:

        // pre-calc some bounds so dragBoundFunc has less calc's to do
        var height=orangeRect.getHeight();
        var minX=white.getX();
        var maxX=white.getX()+white.getWidth()-orangeRect.getWidth();
        var minY=white.getY();
        var maxY=white.getY()+white.getHeight()-orangeRect.getHeight();
    

    That way your dragBoundFunc can just test the current position against these pre-calc’ed bounds like this:

          dragBoundFunc: function(pos) {
              var X=pos.x;
              var Y=pos.y;
              if(XmaxX){X=maxX;}
              if(YmaxY){Y=maxY;}
              return({x:X, y:Y});
          }
    

    Here’s code and a Fiddle: http://jsfiddle.net/m1erickson/n5xMs/

    
    
      
        
      
        
          

    0 讨论(0)
提交回复
热议问题