2017-06-02 124 views

回答

0

這是我用左/上/右/下鍵簡單地實現移動選擇的對象/組:

https://jsfiddle.net/milanhlinak/4fofjzvm/

<!DOCTYPE html> 
<html> 

<head> 
    <script type="text/javascript" src="lib/jquery-3.1.1.min.js"></script> 
    <script type="text/javascript" src="lib/fabric.min.js"></script> 
</head> 

<body> 

    <canvas id="canvas" style="border: 1px solid #cccccc"></canvas> 

    <script> 
     const STEP = 10; 

     var Direction = { 
      LEFT: 0, 
      UP: 1, 
      RIGHT: 2, 
      DOWN: 3 
     }; 

     var canvas = new fabric.Canvas('canvas', { 
      width: 500, 
      height: 500, 
     }); 

     canvas.add(new fabric.Rect({ 
      left: 100, 
      top: 100, 
      width: 50, 
      height: 50, 
      fill: '#faa' 

     })); 
     canvas.add(new fabric.Rect({ 
      left: 300, 
      top: 300, 
      width: 50, 
      height: 50, 
      fill: '#afa' 
     })); 

     fabric.util.addListener(document.body, 'keydown', function (options) { 
      if (options.repeat) { 
       return; 
      } 
      var key = options.which || options.keyCode; // key detection 
      if (key === 37) { // handle Left key 
       moveSelected(Direction.LEFT); 
      } else if (key === 38) { // handle Up key 
       moveSelected(Direction.UP); 
      } else if (key === 39) { // handle Right key 
       moveSelected(Direction.RIGHT); 
      } else if (key === 40) { // handle Down key 
       moveSelected(Direction.DOWN); 
      } 
     }); 

     function moveSelected(direction) { 

      var activeObject = canvas.getActiveObject(); 
      var activeGroup = canvas.getActiveGroup(); 

      if (activeObject) { 
       switch (direction) { 
       case Direction.LEFT: 
        activeObject.setLeft(activeObject.getLeft() - STEP); 
        break; 
       case Direction.UP: 
        activeObject.setTop(activeObject.getTop() - STEP); 
        break; 
       case Direction.RIGHT: 
        activeObject.setLeft(activeObject.getLeft() + STEP); 
        break; 
       case Direction.DOWN: 
        activeObject.setTop(activeObject.getTop() + STEP); 
        break; 
       } 
       activeObject.setCoords(); 
       canvas.renderAll(); 
       console.log('selected objects was moved'); 
      } else if (activeGroup) { 
       switch (direction) { 
       case Direction.LEFT: 
        activeGroup.setLeft(activeGroup.getLeft() - STEP); 
        break; 
       case Direction.UP: 
        activeGroup.setTop(activeGroup.getTop() - STEP); 
        break; 
       case Direction.RIGHT: 
        activeGroup.setLeft(activeGroup.getLeft() + STEP); 
        break; 
       case Direction.DOWN: 
        activeGroup.setTop(activeGroup.getTop() + STEP); 
        break; 
       } 
       activeGroup.setCoords(); 
       canvas.renderAll(); 
       console.log('selected group was moved'); 
      } else { 
       console.log('no object selected'); 
      } 

     } 
    </script> 

</body> 

</html>