當你做box2.setX和box2.setY之後,你還必須重畫你的layer - 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>
真棒小提琴和解釋marke!謝謝!我想知道,如果你有更多的時間,想知道如何製作內部盒子?所以如果說我喜歡其中4個,並且我開始將它們拖入,而不是讓它們重疊,我想讓它們疊加一個呢?任何建議將不勝感激....小提琴更是如此:p – TriFu
要對齊捕捉,使用積累寬度(或高度)的變量來抵消「捕捉」。喜歡這個小提琴:http://jsfiddle.net/m1erickson/LnwsY/ – markE
嗨,這最後一個小提琴是偉大的,我想知道如何我可以拖動它的小傢伙藍色矩形(使用Kinetic.Group) –