用法
paper.fitToContent({
padding: 20,
allowNewOrigin: 'any'
})
源码
fitToContent: function(gridWidth, gridHeight, padding, opt) {
if (isObject$1(gridWidth)) {
opt = gridWidth;
gridWidth = opt.gridWidth || 1;
gridHeight = opt.gridHeight || 1;
padding = opt.padding || 0;
} else {
opt || (opt = {});
gridWidth = gridWidth || 1;
gridHeight = gridHeight || 1;
padding = padding || 0;
}
var minWidth = Math.max(opt.minWidth || 0, gridWidth);
var minHeight = Math.max(opt.minHeight || 0, gridHeight);
var maxWidth = opt.maxWidth || Number.MAX_VALUE;
var maxHeight = opt.maxHeight || Number.MAX_VALUE;
var newOrigin = opt.allowNewOrigin;
padding = normalizeSides(padding);
var area = ('contentArea' in opt) ? new Rect(opt.contentArea) : this.getContentArea(opt);
var currentScale = this.scale();
var currentTranslate = this.translate();
var sx = currentScale.sx;
var sy = currentScale.sy;
area.x *= sx;
area.y *= sy;
area.width *= sx;
area.height *= sy;
var calcWidth = Math.ceil((area.width + area.x) / gridWidth);
var calcHeight = Math.ceil((area.height + area.y) / gridHeight);
if (!opt.allowNegativeBottomRight) {
calcWidth = Math.max(calcWidth, 1);
calcHeight = Math.max(calcHeight, 1);
}
calcWidth *= gridWidth;
calcHeight *= gridHeight;
var tx = 0;
var ty = 0;
if ((newOrigin === 'negative' && area.x < 0) || (newOrigin === 'positive' && area.x >= 0) || newOrigin === 'any') {
tx = Math.ceil(-area.x / gridWidth) * gridWidth;
tx += padding.left;
calcWidth += tx;
}
if ((newOrigin === 'negative' && area.y < 0) || (newOrigin === 'positive' && area.y >= 0) || newOrigin === 'any') {
ty = Math.ceil(-area.y / gridHeight) * gridHeight;
ty += padding.top;
calcHeight += ty;
}
calcWidth += padding.right;
calcHeight += padding.bottom;
calcWidth = Math.max(calcWidth, minWidth);
calcHeight = Math.max(calcHeight, minHeight);
calcWidth = Math.min(calcWidth, maxWidth);
calcHeight = Math.min(calcHeight, maxHeight);
var computedSize = this.getComputedSize();
var dimensionChange = calcWidth != computedSize.width || calcHeight != computedSize.height;
var originChange = tx != currentTranslate.tx || ty != currentTranslate.ty;
if (originChange) {
this.translate(tx, ty);
}
if (dimensionChange) {
this.setDimensions(calcWidth, calcHeight);
}
return new Rect(-tx / sx, -ty / sy, calcWidth / sx, calcHeight / sy);
}