最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - FabricJs - zoom canvas to fit object - Stack Overflow

programmeradmin4浏览0评论

I'm trying to set zoom to canvas in order to fit an object higher than the original canvas height. Here is a fiddle. If you notice, I want the canvas zoomed as it is if you unment these lines:

//canvas.zoomToPoint(new fabric.Point(10, 10), 0.75);
//canvas.renderAll();

I want to programmatically define the correct zoom (for this example, it's 0.75) based on the objects on the canvas.

I'm trying to set zoom to canvas in order to fit an object higher than the original canvas height. Here is a fiddle. If you notice, I want the canvas zoomed as it is if you unment these lines:

//canvas.zoomToPoint(new fabric.Point(10, 10), 0.75);
//canvas.renderAll();

I want to programmatically define the correct zoom (for this example, it's 0.75) based on the objects on the canvas.

Share Improve this question edited Jun 1, 2016 at 17:09 Luke Taylor 9,6489 gold badges60 silver badges96 bronze badges asked Jun 1, 2016 at 12:43 TorgiaTorgia 3284 silver badges14 bronze badges 2
  • Unclear what you ant to achieve - you and to automatically zoom to the size that ALL present on canvas objects are fully visible or smth else? – shershen Commented Jun 1, 2016 at 15:14
  • yes, it's correct, but i often have only one object at a time on the canvas – Torgia Commented Jun 1, 2016 at 15:32
Add a ment  | 

2 Answers 2

Reset to default 8

Resolved with :

canvas.zoomToPoint(new fabric.Point(canvas.width / 2, canvas.height / 2), (canvas.height / obj.height));
    canvas.renderAll();

If you want to fit multiple objects use this:


fabric.Canvas.prototype.zoomToFitObjects = function () {
  if (this.getObjects().length < 1) {
    return;
  }
  let x1 = Math.min(
    ...this.getObjects().map((obj) => obj.left!)
  );
  let y1 = Math.min(
    ...this.getObjects().map((obj) => obj.top!)
  );
  let x2 = Math.max(
    ...this.getObjects().map((obj) => obj.left!)
  );
  let y2 = Math.max(
    ...this.getObjects().map((obj) => obj.top!)
  );
  let height = Math.abs(y1) + Math.abs(y2);
  let width = Math.abs(x1) + Math.abs(x2);
  this.setZoom(1);
  const x = (x1 + (width / 2)) - (this.width! / 2);
  const y = (y1 + (height / 2)) - (this.height! / 2);
  this.absolutePan({ x: x, y: y});
  const heightDist = this.getHeight() - height;
  const widthDist = this.getWidth() - width;
  let groupDimension = 0;
  let canvasDimension = 0;
  if (heightDist < widthDist) {
    groupDimension = height;
    canvasDimension = this.getHeight();
  } else {
    groupDimension = width;
    canvasDimension = this.getWidth();
  }
  const zoom = (canvasDimension / groupDimension) * 0.7;
  this.zoomToPoint({ x: this.width!/2, y: this.height!/2 }, zoom);
};
发布评论

评论列表(0)

  1. 暂无评论