Jquery拖放并在kineticJS中捕捉到网格

时间:2012-02-29 06:05:03

标签: jquery image drag-and-drop kineticjs

嘿我正在使用Kineticjs实现拖放操作 现在我希望图像在它们接近时互相捕捉。 我在KineticJs看到了海滩上的动物,这对我的功能毫无帮助 然后看到jquery捕捉到网格的东西..但是如果我使用它然后我将不得不摆脱KineticJs。我以任何方式实现jquery snap属于kineticJs中的元素 因为在jquery中他们已经传递了img的id以使其可拖动然后捕捉。 那么如何在我的kinetic.js图像中使用它呢

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

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

由于

与Ashish

2 个答案:

答案 0 :(得分:5)

如果你想要捕捉到nxm网格的东西,你需要添加一个调用一个捕获它的函数的监听器。你可能想在“dragend”

这样做

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

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

...方形瓷砖的100x100网格

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

例如:如果YourObject.x = 325,那么你将拥有Math.floor(3.25)* 100 + 50 = 350.左边和顶部都应该是300,而中心是350。

编辑,哎呀错过了部分问题。为了捕捉到其他方块,这就是我要做的事情:

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;
        }
   }
}

答案 1 :(得分:0)

我首先创建网格

    var grid = new Array(gridSize);
    for (var row = 0; row < gridSize; row++) {
      grid[row] = new Array(gridSize);// the columns
    }

然后我得到了单元格

   function current_cell(mousePos) {
      var x = mousePos.x + half_column_width;
      var y = mousePos.y + half_column_height;
      if ( (x < column_width) || (y < column_height) || (x > board_width + column_width) || (y > board_height + column_height) ) {
        return false;
      }
      x = Math.min(x, (board_width * column_width) + column_width);
      y = Math.min(y, (board_height * column_height) + column_height);
      cell_x = Math.floor(x / column_width);
      cell_y = Math.floor(y / column_height);
      if (grid[cell_x][cell_y] == undefined) { 
        grid[cell_x][cell_y] = {};
      }
      var cell = grid[cell_x][cell_y];
      cell.cell_x = cell_x;
      cell.cell_y = cell_y;
      cell.x = cell_x * piece_width;
      cell.y = cell_y * piece_height;
      return cell;
    }

然后在mousemove上

shape.on('dragmove', function() {

  var mousePos = stage.getMousePosition();
  cell = current_cell(mousePos)
  shape.setPosition(cell.x, cell.y);
});