使用 Fabric 缩放到 canvas 的中心

Zoom to the centre of canvas using Fabric

我正在使用 fabric.js 在 canvas 上实现缩放功能。我实现了缩放,但不知何故它没有缩放到 canvas 的中心。它缩放到 canvas.

的左上角

下面是我的 JS。

<script>
  var canvas = new fabric.Canvas("Canvas-Id", {
    selection: true,
    width: 800,
    height: 400
  });

  canvas.setBackgroundImage('http://i24.photobucket.com/albums/c22/smeagolsfree/TSCHQ.png', canvas.renderAll.bind(canvas), {
    width: canvas.width,
    height: canvas.height
  });

  initializeCanvas(canvas)

</script>

在我的 JS 文件中:

var initializeCanvas;

initializeCanvas = function(canvas) {
  var MAX_ZOOM_IN, MAX_ZOOM_OUT, SCROLL_SIZE, ZOOM_PERCENT, zoomIn, zoomOut;
  SCROLL_SIZE = 120;
  ZOOM_PERCENT = 1.2;
  MAX_ZOOM_IN = 5;
  MAX_ZOOM_OUT = 1;

  zoomIn = function() {
    if(canvas.getZoom() < MAX_ZOOM_IN) {
      canvas.setZoom(canvas.getZoom() * ZOOM_PERCENT);
      $('.flaticon-zoom-in').removeClass('disable');
    } else {
      $('.flaticon-zoom-in').addClass('disable');
    }
    $('.flaticon-zoom-out').removeClass('disable');
  };

  zoomOut = function() {
    if(canvas.getZoom() > MAX_ZOOM_OUT) {
      canvas.setZoom(canvas.getZoom() / ZOOM_PERCENT);
      $('.flaticon-zoom-out').removeClass('disable');
    } else {
      $('.flaticon-zoom-out').addClass('disable');
    }
    $('.flaticon-zoom-in').removeClass('disable');
  };

  $('#zoomIn').click(function() {
    zoomIn();
  });

  $('#zoomOut').click(function() {
    zoomOut();
  });

  $('.taggable-image-canvas-container').bind('mousewheel', function(e) {
    e.preventDefault();
    (e.originalEvent.wheelDelta / SCROLL_SIZE > 0) ? zoomIn() : zoomOut()
  });
};

任何人都可以建议我如何实现缩放到 canvas 的中心。

这是 setZoom 函数的预期行为,它以左上角的点作为参数调用 zoomToPoint:

setZoom: function (value) {
  this.zoomToPoint(new fabric.Point(0, 0), value);
  return this;
}

因此,可以通过调用 zoomToPoint:

来实现 canvas 中心的缩放
canvas.zoomToPoint(new fabric.Point(canvas.width / 2, canvas.height / 2), canvas.getZoom() / ZOOM_PERCENT);