2013-03-02 2 views
0

Как я могу изменить этот код, а не перетаскивать вас, просто нажмите два элемента, чтобы обменять положение двух элементов? Я хотел обменять две плитки, щелкнув одну другую, но вместо этого здесь нужно перетащить первую плитку, чтобы перевести ее в другую, а затем обменять.Как сменить мышь на onclick

function onPuzzleClick(e){ 
     if(e.layerX || e.layerX == 0){ 
      _mouse.x = e.layerX - _canvas.offsetLeft; 
      _mouse.y = e.layerY - _canvas.offsetTop; 
     } 
     else if(e.offsetX || e.offsetX == 0){ 
      _mouse.x = e.offsetX - _canvas.offsetLeft; 
      _mouse.y = e.offsetY - _canvas.offsetTop; 
     } 
     _currentPiece = checkPieceClicked(); 
     if(_currentPiece != null){ 
      _stage.clearRect(_currentPiece.xPos,_currentPiece.yPos,pcWidth,pcHeight); 
      _stage.save(); 
      _stage.globalAlpha = .9; 
      _stage.drawImage(_img, _currentPiece.sx, _currentPiece.sy, pcWidth, pcHeight, _mouse.x - (pcWidth/2), _mouse.y - (pcHeight/2), pcWidth, pcHeight); 
      _stage.restore(); 
      document.onmousemove = updatePuzzle; 
      document.onmouseup = pieceDropped; 
     } 
    } 
    function checkPieceClicked(){ 
     var i; 
     var piece; 
     for(i = 0;i < _pieces.length;i++){ 
      piece = _pieces[i]; 
      if(_mouse.x < piece.xPos || _mouse.x > (piece.xPos + pcWidth) || _mouse.y < piece.yPos || _mouse.y > (piece.yPos + pcHeight)){ 
       //PIECE NOT HIT 
      } 
      else{ 
       return piece; 
      } 
     } 
     return null; 
    } 
    function updatePuzzle(e){ 
     _currentDropPiece = null; 
     if(e.layerX || e.layerX == 0){ 
      _mouse.x = e.layerX - _canvas.offsetLeft; 
      _mouse.y = e.layerY - _canvas.offsetTop; 
     } 
     else if(e.offsetX || e.offsetX == 0){ 
      _mouse.x = e.offsetX - _canvas.offsetLeft; 
      _mouse.y = e.offsetY - _canvas.offsetTop; 
     } 
     _stage.clearRect(0,0,width,height); 
     var i; 
     var piece; 
     for(i = 0;i < _pieces.length;i++){ 
      piece = _pieces[i]; 
      if(piece == _currentPiece){ 
       continue; 
      } 
      _stage.drawImage(_img, piece.sx, piece.sy, pcWidth, pcHeight, piece.xPos, piece.yPos, pcWidth, pcHeight); 
      _stage.strokeRect(piece.xPos, piece.yPos, pcWidth,pcHeight); 
      if(_currentDropPiece == null){ 
       if(_mouse.x < piece.xPos || _mouse.x > (piece.xPos + pcWidth) || _mouse.y < piece.yPos || _mouse.y > (piece.yPos + pcHeight)){ 
        //NOT OVER 
       } 
       else{ 
        _currentDropPiece = piece; 
        _stage.save(); 
        _stage.globalAlpha = .4; 
        _stage.fillStyle = PUZZLE_HOVER_TINT; 
        _stage.fillRect(_currentDropPiece.xPos,_currentDropPiece.yPos,pcWidth, pcHeight); 
        _stage.restore(); 
       } 
      } 
     } 
     _stage.save(); 
     _stage.globalAlpha = .6; 
     _stage.drawImage(_img, _currentPiece.sx, _currentPiece.sy, pcWidth, pcHeight, _mouse.x - (pcWidth/2), _mouse.y - (pcHeight/2), pcWidth, pcHeight); 
     _stage.restore(); 
     _stage.strokeRect(_mouse.x - (pcWidth/2), _mouse.y - (pcHeight/2), pcWidth,pcHeight); 
    } 
    function pieceDropped(e){ 
     document.onmousemove = null; 
     document.onmouseup = null; 
     if(_currentDropPiece != null){ 
      var tmp = {xPos:_currentPiece.xPos,yPos:_currentPiece.yPos}; 
      _currentPiece.xPos = _currentDropPiece.xPos; 
      _currentPiece.yPos = _currentDropPiece.yPos; 
      _currentDropPiece.xPos = tmp.xPos; 
      _currentDropPiece.yPos = tmp.yPos; 

ответ

0

Вот как поменять части с помощью щелчков мыши, а не тащит

В обработчике MouseUp:

  • Проверьте, если пользователь попал какой-либо части.

  • Если пользователь ударил кусок и ни одна деталь ранее не была выбрана, выберите «этот».

  • Если пользователь ударил кусок и там был как предыдущий выбор, затем поменяйте 2 части и сбросьте части.

  • Если пользователь нажимает за пределы всех частей, очистите любую «выбранную» деталь.

Вот рабочий код для вас, чтобы посмотреть и скрипку: http://jsfiddle.net/m1erickson/a75xz/

<!doctype html> 
<html> 
<head> 
<link rel="stylesheet" type="text/css" media="all" href="css/reset.css" /> <!-- reset css --> 
<script type="text/javascript" src="http://code.jquery.com/jquery.min.js"></script> 

<style> 
    body{ background-color: ivory; } 
    canvas{border:1px solid red;} 
</style> 

<script> 
$(function(){ 

    var canvas=document.getElementById("canvas"); 
    var ctx=canvas.getContext("2d"); 
    var canvasOffset=$("#canvas").offset(); 
    var offsetX=canvasOffset.left; 
    var offsetY=canvasOffset.top; 
    var canvasWidth=canvas.width; 
    var canvasHeight=canvas.height; 

    // create "pieces" 
    var selectedPiece=-1; 
    var pieceSize=75; 
    var pieces=[]; 
    pieces.push({x:50,y:30,color:"orange"}); 
    pieces.push({x:150,y:30,color:"green"}); 
    pieces.push({x:250,y:30,color:"blue"}); 
    for(var x=0;x<pieces.length;x++){ 
     drawPiece(x,false); 
    } 

    // draw the specified piece 
    // stroke it in red if it's selected 
    function drawPiece(pieceId,isStroked){ 
     if(pieceId<0){return;} 
     var piece=pieces[pieceId]; 
     ctx.save(); 
     ctx.beginPath(); 
     ctx.fillStyle=piece.color; 
     ctx.rect(piece.x,piece.y,pieceSize,pieceSize); 
     ctx.fill(); 
     ctx.strokeStyle=(isStroked ? "red" : "black"); 
     ctx.lineWidth=6; 
     ctx.stroke(); 
     ctx.fillStyle="white"; 
     ctx.font = 'italic 18px Calibri'; 
     ctx.fillText("Box#"+pieceId,piece.x+15,piece.y+25); 
     ctx.restore(); 
    } 

    function hitTest(x,y){ 
     var hit=-1; 
     for(var pieceId=0;pieceId<pieces.length;pieceId++){ 
      piece=pieces[pieceId]; 
      var isHit=!(x<piece.x || x>(piece.x + pieceSize) || y<piece.y || y>(piece.y + pieceSize)); 
      if(isHit){ 
       hit=pieceId; 
       break; // Hit! We're outta here... 
      } 
     } 
     return(hit); // returns piece# if hit else -1 to indicate no hits 
    } 

    function handleMouseUp(e){ 
     canMouseX=parseInt(e.clientX-offsetX); 
     canMouseY=parseInt(e.clientY-offsetY); 

     // de-highlight previous selection, if any 
     drawPiece(selectedPiece,false) 

     // did we hit a piece? 
     var hit=hitTest(canMouseX,canMouseY); 

     // if no-hit, the user clicked outside a box 
     // so clear the selectedPiece and we're outta here 
     if(hit<0){ 
      drawPiece(selectedPiece,false) 
      selectedPiece=-1; 
      return; 
     } 

     // Hit! 
     // if no previous selection, 
     // set selectedPiece and highlight selectedPiece 
     if(selectedPiece<0){ 
       selectedPiece=hit; 
       drawPiece(selectedPiece,true); 
     } 
     // else, there was a piece already selected 
     // so swap these pieces! 
     else{ 
      var s=pieces[selectedPiece]; 
      var h=pieces[hit]; 
      var temp={x:s.x, y:s.y}; 
      s.x=h.x; 
      s.y=h.y; 
      h.x=temp.x; 
      h.y=temp.y; 
      drawPiece(selectedPiece,false); 
      drawPiece(hit,false); 
      selectedPiece=-1; // clear 
     } 

    } // end handleMouseDown() 

    $("#canvas").mouseup(function(e){handleMouseUp(e);}); 


}); // end $(function(){}); 
</script> 

</head> 

<body> 
    <br/><p>Click once to select a box</p> 
    <p>Click a second box to swap the boxes</p> 
    <canvas id="canvas" width=400 height=300></canvas> 
</body> 
</html> 
Смежные вопросы