@image/packer
Version:
image packer
92 lines (91 loc) • 3.5 kB
JavaScript
var MultiBinPacker = (function () {
function MultiBinPacker(maxWidth, maxHeight, padding) {
this.bins = [];
this.oversizedElements = [];
this.maxWidth = maxWidth;
this.maxHeight = maxHeight;
this.padding = padding;
}
MultiBinPacker.prototype.add = function (data) {
if (data.width > this.maxWidth || data.height > this.maxHeight) {
this.oversizedElements.push(data);
}
else {
var added = this.bins.find(function (bin) { return !!bin.add(data); });
if (!added) {
var bin = new BinaryTreeBin(this.maxWidth, this.maxHeight, this.padding);
bin.add(data);
this.bins.push(bin);
}
}
};
MultiBinPacker.prototype.sort = function (rects) {
return rects.slice().sort(function (a, b) { return Math.max(b.width, b.height) - Math.max(a.width, a.height); });
};
MultiBinPacker.prototype.addArray = function (rects) {
var _this = this;
this.sort(rects).forEach(function (rect) { return _this.add(rect); });
};
return MultiBinPacker;
}());
export { MultiBinPacker };
var BinaryTreeBin = (function () {
function BinaryTreeBin(maxWidth, maxHeight, padding) {
this.width = 0;
this.height = 0;
this.maxWidth = maxWidth;
this.maxHeight = maxHeight;
this.padding = padding || 0;
this.rootNode = { x: 0, y: 0, width: maxWidth + this.padding, height: maxHeight + this.padding };
this.rects = [];
}
BinaryTreeBin.prototype.add = function (data) {
var node = this.findNode(this.rootNode, data.width + this.padding, data.height + this.padding);
if (node) {
node.children = this.createChildren(node, data.width + this.padding, data.height + this.padding);
this.width = Math.max(this.width, node.x + data.width);
this.height = Math.max(this.height, node.y + data.height);
var rect = { width: data.width, height: data.height, x: node.x, y: node.y, data: data };
this.rects.push(rect);
return rect;
}
return undefined;
};
BinaryTreeBin.prototype.findNode = function (node, width, height) {
if (node.children) {
for (var i = 0; i < node.children.length; i++) {
var found = this.findNode(node.children[i], width, height);
if (found) {
return found;
}
}
return undefined;
}
if ((width <= node.width) && (height <= node.height)) {
return node;
}
return undefined;
};
BinaryTreeBin.prototype.createChildren = function (node, width, height) {
var children = [];
if (node.height - height > 0 && node.x < this.maxWidth) {
children.push({
x: node.x,
y: node.y + height,
width: node.width,
height: node.height - height
});
}
if (node.width - width > 0 && node.y < this.maxHeight) {
children.push({
x: node.x + width,
y: node.y,
width: node.width - width,
height: height
});
}
return children;
};
return BinaryTreeBin;
}());
export { BinaryTreeBin };