Search code examples
jqueryimagedrag-and-dropkineticjs

Jquery drag and drop and snap to grid in kineticJS


Hey I am implementing the drag and drop operations using Kineticjs Now I want the images to snap to each other if they get close .. I saw the animals on beach example in KineticJs which was no help to me for my functionality then saw the jquery snap to grid thing..But if I use that then I'll have to get rid of KineticJs .Is thr any way to implement jquery snap propery to the elements in kineticJs cause in jquery they have passed the id of the img to make it draggable and then snap. So how can I use this with my kinetic.js images

jquery draggable: http://jqueryui.com/demos/draggable/#snap-to

kinetic.js: http://www.kineticjs.com/

Thanks

Ashish


Solution

  • If you're going for something that snaps to an nxm grid you'd want to add a listener that calls a function which snaps it. You'd probably want to do this at "dragend"

    http://www.html5canvastutorials.com/kineticjs/html5-canvas-drag-and-drop-events-tutorial/

      box.on("dragend", function(){
        snaptogrid(box);
      });
    

    ... 100x100 grid for square tiles

      function snaptogrid(YourObject){
         YourObject.x = Math.floor(YourObject.x/100) * 100 + 50;
         YourObject.y = Math.floor(YourObject.y/100) * 100 + 50;
      }
    

    ex: if YourObject.x = 325, then you'll have Math.floor(3.25)*100+50 = 350. The left and top should both be at 300, while, the center is at 350.

    Edit, oops missed part of the question. For snapping to other squares, here's what I'd do:

    function snaptoOther(YourSquares, index){
       var lastone = YourSquares.length-1;
       var maxDist = 125;
       var minDist = 75;
       var squarelength = 100;
    
       for(var i=0; i<lastone; i++)
       {
         var checkx = abs(YourSquares[index].x - YourSquares[i].x);
         var checky = abs(YourSquares[index].y - YourSquares[i].y);
         var multiplyX = Math.round((YourSquares[index].x - YourSquares[i].x)/squarelength);
         var multiplyY = Math.round((YourSquares[index].y - YourSquares[i].y)/squarelength);
    
          if(checkx < maxDist && checkx > minDist && i !== index)
            {
              YourSquares[index].x = YourSquares[i].x + multiplyX*squarelength;
            }
          if(checky < maxDist && checky > minDist && i !== index)
            {
              YourSquares[index].y = YourSquares[i].y + multiplyY*squarelength;
            }
       }
    }