使用Fabric将画布缩放到中心

5

我正在使用fabric.js在画布上实现缩放功能。我已经实现了缩放,但是它不会缩放到画布中心,而是缩放到左上角。

以下是我的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()
  });
};

有人能为我提供如何实现画布居中缩放的建议吗?

1个回答

12

setZoom函数调用zoomToPoint函数,并将左上角点作为参数传递是预期的行为:

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

因此,通过调用zoomToPoint可以实现对画布中心的缩放:

canvas.zoomToPoint(new fabric.Point(canvas.width / 2, canvas.height / 2), canvas.getZoom() / ZOOM_PERCENT);

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接