Commit c0992a69 authored by rockyl's avatar rockyl

优化图集打包的尺寸

parent 05a560fa
...@@ -10,6 +10,10 @@ import generateUUID from "uuid/v4"; ...@@ -10,6 +10,10 @@ import generateUUID from "uuid/v4";
const packExts = ['.png']; //, '.jpg', '.jpeg', '.bmp' const packExts = ['.png']; //, '.jpg', '.jpeg', '.bmp'
let canvas = document.createElement('canvas'); let canvas = document.createElement('canvas');
let canvasFinal = document.createElement('canvas');
let context = canvas.getContext('2d');
let contextFinal = canvasFinal.getContext('2d');
export async function packImages(assets, options = {}) { export async function packImages(assets, options = {}) {
const padding = options.padding || 1; const padding = options.padding || 1;
...@@ -60,16 +64,24 @@ export async function packImages(assets, options = {}) { ...@@ -60,16 +64,24 @@ export async function packImages(assets, options = {}) {
let pack = new MaxRectsBinPack(maxSize, maxSize, false); let pack = new MaxRectsBinPack(maxSize, maxSize, false);
let packedRects = pack.insertRects(remainRects, mode); let packedRects = pack.insertRects(remainRects, mode);
//document.body.append(canvas);
canvas.width = canvas.height = maxSize; canvas.width = canvas.height = maxSize;
let context = canvas.getContext('2d'); let maxWidth = 0, maxHeight = 0;
//context.fillStyle = `rgba(${Math.floor(Math.random() * 256)}, ${Math.floor(Math.random() * 256)}, ${Math.floor(Math.random() * 256)}, 1)`;
//context.strokeRect(0, 0, maxSize, maxSize);
for (let rect of packedRects) { for (let rect of packedRects) {
if (rect.x + rect.width > maxWidth) {
maxWidth = rect.x + rect.width;
}
if (rect.y + rect.height > maxHeight) {
maxHeight = rect.y + rect.height;
}
context.drawImage(rect.image, rect.x + padding, rect.y + padding); context.drawImage(rect.image, rect.x + padding, rect.y + padding);
} }
canvasFinal.width = maxWidth;
canvasFinal.height = maxHeight;
contextFinal.drawImage(canvas, 0, 0);
let blob = await new Promise(resolve => { let blob = await new Promise(resolve => {
canvas.toBlob(function (blob) { canvasFinal.toBlob(function (blob) {
resolve(blob); resolve(blob);
}, 'image/png'); }, 'image/png');
}); });
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment