Fabric.js Canvas Zoom and Pan

Implementation of Fabric.js canvas zoom and pan.

by Maiki Nahara

HTML

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/fabric.js/1.7.1/fabric.min.js"></script>
<body>
  <canvas id="canvas" style="border: 1px solid #cccccc"></canvas>
</body>

JavaScript

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

var zoomLevel = 0;
var zoomLevelMin = 0;
var zoomLevelMax = 3;

var shiftKeyDown = false;
var mouseDownPoint = null;

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

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

canvas.on('mouse:down', function(options) {
  var pointer = canvas.getPointer(options.e, true);
  mouseDownPoint = new fabric.Point(pointer.x, pointer.y);
});
canvas.on('mouse:up', function(options) {
  mouseDownPoint = null;
});
canvas.on('mouse:move', function(options) {
  if (shiftKeyDown && mouseDownPoint) {
    var pointer = canvas.getPointer(options.e, true);
    var mouseMovePoint = new fabric.Point(pointer.x, pointer.y);
    canvas.relativePan(mouseMovePoint.subtract(mouseDownPoint));
    mouseDownPoint = mouseMovePoint;
    keepPositionInBounds(canvas);
  }
});

fabric.util.addListener(document.body, 'keydown', function(options) {
  if (options.repeat) {
    return;
  }
  var key = options.which || options.keyCode; // key detection
  if (key == 16) { // handle Shift key
    canvas.defaultCursor = 'move';
    canvas.selection = false;
    shiftKeyDown = true;
  } else if (key === 37) { // handle Left key
    move(Direction.LEFT);
  } else if (key === 38) { // handle Up key
    move(Direction.UP);
  } else if (key === 39) { // handle Right key
    move(Direction.RIGHT);
  } else if (key === 40) { // handle Down key
    move(Direction.DOWN);
  }
});
fabric.util.addListener(document.body, 'keyup', function(options) {
  var key = options.which || options.keyCode; // key detection
  if (key == 16) { // handle Shift key
    canvas.defaultCursor = 'default';
    canvas.selection = true;
    shiftKeyDown = false;
  }
});
jQuery('.canvas-container').on('mousewheel', function(options)...