如何更改此代码而不是拖动您只需单击两个元素即可交换两个元素的位置?我想通过单击一个然后另一个来交换两个图块,但是在这里您需要拖动第一个图块将其带到另一个图块然后它们将交换。
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;