我正在尝试将缩放设置为画布,以适应高于原始画布高度的对象。 这是一把小提琴。如果您注意到,如果您取消注释这些行,我希望画布按原样缩放:
//canvas.zoomToPoint(new fabric.Point(10, 10), 0.75);
//canvas.renderAll();
我想根据画布上的对象以编程方式定义正确的缩放(对于本例,它是
0.75
)。
已解决:
canvas.zoomToPoint(new fabric.Point(canvas.width / 2, canvas.height / 2), (canvas.height / obj.height));
canvas.renderAll();
如果你想适应多个对象,请使用这个:
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);
};