0

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

stage.getUserPosition()

我正在尝试做的事情。

有人可以告诉我我做错了什么或展示一种更好的方法来让拖拽和捕捉工作吗?ps 请不要只给我发送一个链接到 html5canvastutorials 上的动物捕捉示例,因为我已经看到它处理图像并且我正在处理形状。

4

1 回答 1

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>
于 2013-05-18T17:20:01.127 回答