【问题标题】:Zoom to the centre of canvas using Fabric使用 Fabric 缩放到画布中心
【发布时间】:2015-06-21 08:14:26
【问题描述】:

我正在使用 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()
  });
};

谁能建议我如何实现缩放到画布中心。

【问题讨论】:

    标签: jquery canvas fabricjs zooming


    【解决方案1】:

    这是 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);
    

    【讨论】:

      猜你喜欢
      • 2018-03-20
      • 2021-07-23
      • 2020-04-08
      • 2016-12-28
      • 1970-01-01
      • 2023-03-08
      • 2020-08-19
      • 1970-01-01
      • 2011-10-10
      相关资源
      最近更新 更多