Kineticjs dragBoundFunc for a rect in a rect

Capoism

New Member
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 solution for this behavior?? that the bigger rect is the dragborder for the small rect??And another question... would it be possible to do it for a rect in any polygon as border?\[code\]<!DOCTYPE HTML><html><head> <style> body {margin: 0px; padding: 20px;} canvas {border: 1px solid #777;} </style></head><body><div id="container"></div><script src="http://d3lp1msu2r81bx.cloudfront.net/kjs/js/lib/kinetic-v4.3.2.js"></script><script> var stage = new Kinetic.Stage({ container: 'container', width: 300, height: 300 }); var layer = new Kinetic.Layer(); // White box var white = new Kinetic.Rect({ x: 100, y: 50, width: 150, height: 100, fill: 'white', stroke: 'black', strokeWidth: 2 }); // orange box var orange = new Kinetic.Rect({ x: 150, y: 100, width: 50, height: 30, fill: 'orange', stroke: 'black', strokeWidth: 2, draggable: true, // this causes orange box to be stopped if try to leave white box dragBoundFunc: function(pos){ if(theyAreColliding(orange,white)){ // orange box is touching white box // let it move ahead return ({ x:pos.x, y:pos.y }); } else{ // orange box is not touching white box // don't let orange box move outside if (white.getY() > orange.getY()){ return({x: pos.x, y: white.getY()+1}); } else if (white.getY() + white.getHeight() - orange.getHeight() < orange.getY()){ return({x: pos.x, y: white.getY() + white.getHeight() - orange.getHeight() -1}); } else if (white.getX() > orange.getX()){ return({x: white.getX() +1, y: pos.y}) } else if (white.getX() + white.getWidth() - orange.getWidth() < orange.getX()){ return({x: white.getX() +white.getWidth() - orange.getWidth() -1, y: pos.y}) } } } }); function theyAreColliding(rect1, rect2) { return !(rect2.getX() > rect1.getX() || rect2.getX() + rect2.getWidth() - rect1.getWidth() < rect1.getX() || rect2.getY() > rect1.getY() || rect2.getY() + rect2.getHeight() - rect1.getHeight() < rect1.getY()); } layer.add(white); layer.add(orange); stage.add(layer);</script></body></html>\[/code\]and also the jsfiddle link: http://jsfiddle.net/dNfjM/
 
Back
Top