kineticjs snap rect到另一个rect

时间:2013-05-18 10:18:32

标签: drag-and-drop kineticjs

我正在使用kineticjs尝试将一个小矩形拖动到一个更大的矩形中并使其卡入到位。但是,当我尝试使用时出现错误:

stage.getUserPosition()

我试图做的fiddle

有人可以告诉我我做错了什么或者说出更好的方法来阻止和捕捉工作吗? 附:请不要只是给我发一个关于html5canvastutorials上的动物捕捉示例的链接,因为我已经看过它并且它处理图像而我正在处理形状。

1 个答案:

答案 0 :(得分:1)

执行box2.setX和box2.setY后,还必须重绘图层 - layer.draw()。

box2.on("dragend",function(){
    if(isInside(this)){
        box2.setX(box.getX());
        box2.setY(box.getY());
        layer.draw();
    }
});

由于您的设计非常简单,只需使用矩形边界检查以查看box2是否在框内:

var dropLeft=box.getX();
var dropRight=dropLeft+box.getWidth();
var dropTop=box.getY();
var dropBottom=dropTop+box.getHeight();

function isInside(shape){
    var x=box2.getX();
    var y=box2.getY();
    var w=box2.getWidth();
    var h=box2.getHeight();
    return(x>=dropLeft && x+w<=dropRight && y>=dropTop && y+h<=dropBottom);
}

这是代码和小提琴:http://jsfiddle.net/m1erickson/ymhfM/

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <title>Prototype</title>
    <script type="text/javascript" src="http://code.jquery.com/jquery.min.js"></script>
    <script src="http://www.html5canvastutorials.com/libraries/kinetic-v4.3.3-beta.js"></script>

<style>
#container{
  border:solid 1px #ccc;
  margin-top: 10px;
  width:400px;
}
</style>        
<script>
$(function(){

    var stage = new Kinetic.Stage({
        container: 'container',
        width: 400,
        height: 400
    });
    var layer = new Kinetic.Layer();
    stage.add(layer);

    // I use a helper function to build Kinetic rectangles
    // You can do it manually if you want to
    var box=kRect(50,100,100,100,"white","green",6,layer);
    var box2=kRect(10,10,30,30,"lightgray","skyblue",3,layer);

    var dropLeft=box.getX();
    var dropRight=dropLeft+box.getWidth();
    var dropTop=box.getY();
    var dropBottom=dropTop+box.getHeight();

    function isInside(shape){
        var x=box2.getX();
        var y=box2.getY();
        var w=box2.getWidth();
        var h=box2.getHeight();
        return(x>=dropLeft && x+w<=dropRight && y>=dropTop && y+h<=dropBottom);
    }

    box2.on("dragmove",function(){
        if(isInside(this)){
            this.setStroke("red");
        }else{
            this.setStroke("skyblue");
        }
    });

    box2.on("dragend",function(){
        if(isInside(this)){
            box2.setX(box.getX());
            box2.setY(box.getY());
            layer.draw();
        }
    });


    // build the specified KineticJS Rectangle and add it to the stage
    function kRect(x,y,width,height,fill,stroke,strokewidth,layer){
      var rect = new Kinetic.Rect({
        x: x,
        y: y,
        width: width,
        height: height,
        fill: fill,
        stroke: stroke,
        strokeWidth: strokewidth,
        draggable:true
      });    
      layer.add(rect);
      stage.draw();
      return(rect);
    }

}); // end $(function(){});

</script>       
</head>

<body>
    <div id="container"></div>
</body>
</html>