import Konva from 'konva';
import { field, input, number, value, background, format, dimensions, encode, result } from '../../src/io.js';
export default {
controls: field('列数', input('columns', 2, 1, 4)) + field('单格宽度(px)', input('cellWidth', 400, 64, 1600)) + field('单格高度(px)', input('cellHeight', 300, 64, 1600)) + field('间距(px)', input('gap', 16, 0, 100)) + background() + format(),
async run({ state, form }) {
if (state.images.length < 2) throw new Error('拼图至少需要两张图片。');
const columns = Math.min(number(form, 'columns'), state.images.length); const rows = Math.ceil(state.images.length / columns);
const cellWidth = number(form, 'cellWidth'); const cellHeight = number(form, 'cellHeight'); const gap = number(form, 'gap');
const width = columns * cellWidth + (columns + 1) * gap; const height = rows * cellHeight + (rows + 1) * gap;
dimensions(width, height);
const stage = new Konva.Stage({ container: document.createElement('div'), width, height });
try {
const layer = new Konva.Layer(); stage.add(layer); layer.add(new Konva.Rect({ width, height, fill: value(form, 'background') }));
state.images.forEach((item, i) => {
const scale = Math.max(cellWidth / item.width, cellHeight / item.height);
const cropWidth = cellWidth / scale; const cropHeight = cellHeight / scale;
layer.add(new Konva.Image({ image: item.image, x: gap + (i % columns) * (cellWidth + gap), y: gap + Math.floor(i / columns) * (cellHeight + gap), width: cellWidth, height: cellHeight, crop: { x: (item.width - cropWidth) / 2, y: (item.height - cropHeight) / 2, width: cropWidth, height: cropHeight } }));
});
layer.draw(); const type = value(form, 'format');
return [result(await encode(stage.toCanvas({ pixelRatio: 1 }), type), `collage.${type === 'image/jpeg' ? 'jpg' : type.split('/')[1]}`, `${width} × ${height}`)];
} finally { stage.destroy(); }
},
};