| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861 |
- /**
- * 导出动画弹出框
- */
- class ExportView {
- constructor() {
- this.overlay = null;
- this.modal = null;
- this.previewImage = null;
- this.previewPlaceholder = null;
- this.referenceBox = null;
- this.referenceInput = null;
- this.referenceUploadArea = null;
- this.referenceImage = null;
- this.referenceImageWrapper = null;
- this.referenceRemoveBtn = null;
- this.replaceBtn = null;
- this.additionalPromptInput = null;
- this.cancelBtn = null;
- this.confirmBtn = null;
- this.imageData = null;
- this.referenceImageData = null;
- this.spritesheetCanvas = null;
- this.folderName = null;
- this.spritesheetLayout = null; // 保存布局信息用于生成 JSON
- this.replacedImageData = null; // 保存 Gemini 返回的替换后的图片(base64)
- this.originalSpritesheetData = null; // 保存原始 spritesheet 的 base64 数据
-
- this.init();
- }
- init() {
- this.overlay = document.getElementById('exportOverlay');
- this.modal = document.getElementById('exportModal');
- this.previewImage = document.getElementById('previewImage');
- this.previewPlaceholder = document.getElementById('previewPlaceholder');
- this.referenceBox = document.getElementById('referenceBox');
- this.referenceInput = document.getElementById('referenceInput');
- this.referenceUploadArea = document.getElementById('referenceUploadArea');
- this.referenceImage = document.getElementById('referenceImage');
- this.referenceImageWrapper = document.getElementById('referenceImageWrapper');
- this.referenceRemoveBtn = document.getElementById('referenceRemoveBtn');
- this.replaceBtn = document.getElementById('replaceBtn');
- this.additionalPromptInput = document.getElementById('additionalPromptInput');
- this.cancelBtn = document.getElementById('exportCancelBtn');
- this.confirmBtn = document.getElementById('exportConfirmBtn');
-
- this.bindEvents();
-
- // 初始时禁用确定按钮
- if (this.confirmBtn) {
- this.confirmBtn.disabled = true;
- }
-
- this.reset();
- }
- bindEvents() {
- // 取消按钮(右上角)
- this.cancelBtn?.addEventListener('click', () => {
- this.close();
- });
- // 取消按钮(底部操作栏)
- this.cancelBtnBottom?.addEventListener('click', () => {
- this.close();
- });
- // 确定按钮
- this.confirmBtn?.addEventListener('click', () => {
- this.handleConfirm();
- });
- // 替换按钮
- this.replaceBtn?.addEventListener('click', () => {
- this.replaceCharacter();
- });
- // 删除参考图按钮
- this.referenceRemoveBtn?.addEventListener('click', (e) => {
- e.stopPropagation(); // 阻止触发父元素的点击事件
- this.removeReferenceImage();
- });
- // 点击遮罩层关闭
- this.overlay?.addEventListener('click', (e) => {
- if (e.target === this.overlay) {
- this.close();
- }
- });
- // ESC键关闭
- document.addEventListener('keydown', (e) => {
- if (e.key === 'Escape' && this.overlay) {
- this.close();
- }
- });
- // 参考图上传区域点击
- this.referenceBox?.addEventListener('click', () => {
- this.referenceInput?.click();
- });
- // 参考图选择
- this.referenceInput?.addEventListener('change', (e) => {
- const file = e.target.files[0];
- if (file) {
- this.loadReferenceImage(file);
- }
- });
- // 拖拽上传参考图
- this.referenceBox?.addEventListener('dragover', (e) => {
- e.preventDefault();
- e.stopPropagation();
- if (this.referenceBox) {
- this.referenceBox.style.borderColor = '#667eea';
- }
- });
- this.referenceBox?.addEventListener('dragleave', (e) => {
- e.preventDefault();
- e.stopPropagation();
- if (this.referenceBox) {
- this.referenceBox.style.borderColor = '#e5e7eb';
- }
- });
- this.referenceBox?.addEventListener('drop', (e) => {
- e.preventDefault();
- e.stopPropagation();
- if (this.referenceBox) {
- this.referenceBox.style.borderColor = '#e5e7eb';
- }
-
- const file = e.dataTransfer.files[0];
- if (file && file.type.startsWith('image/')) {
- this.loadReferenceImage(file);
- }
- });
- // 监听来自父窗口的消息
- window.addEventListener('message', (event) => {
- if (event.data && event.data.type === 'show-export-preview') {
- // console.log('[ExportView] 收到显示预览消息:', event.data);
- this.showPreview(event.data.imageUrl || event.data.imageData);
- } else if (event.data && event.data.type === 'generate-export-preview') {
- // console.log('[ExportView] 收到生成预览消息:', event.data);
- this.reset();
- this.folderName = event.data.folderName;
- this.generatePreview(event.data.folderName);
- }
- });
- }
- /**
- * 生成预览图
- * @param {string} folderName - 文件夹名称
- */
- async generatePreview(folderName) {
- if (!folderName) {
- // console.warn('[ExportView] 没有提供文件夹名称');
- if (this.previewPlaceholder) {
- this.previewPlaceholder.textContent = '没有提供文件夹名称';
- }
- return;
- }
- // 重置状态(确保每次打开都是全新状态)
- this.reset();
- // 保存文件夹名称
- this.folderName = folderName;
- // 显示加载状态
- if (this.previewPlaceholder) {
- this.previewPlaceholder.classList.remove('hide');
- }
- if (this.previewImage) {
- this.previewImage.classList.remove('show');
- }
- try {
- const TEXTURE_ROOT = "http://localhost:3000/disk_data";
-
- // 获取帧列表
- const encodedFolderName = encodeURIComponent(folderName);
- const response = await fetch(`http://localhost:3000/api/frames/${encodedFolderName}`);
-
- if (!response.ok) {
- // 服务端返回错误,解析错误信息
- const errorData = await response.json().catch(() => ({}));
- throw new Error(errorData.error || '无法获取帧列表');
- }
-
- const data = await response.json();
- const frameNumbers = data.frames || [];
- const fileNames = data.fileNames || [];
-
- if (frameNumbers.length === 0) {
- throw new Error('该文件夹中没有图片');
- }
-
- // 加载所有图片
- const images = [];
- for (let i = 0; i < frameNumbers.length; i++) {
- const frameNum = frameNumbers[i];
- const pathSegments = folderName.split('/').map(seg => encodeURIComponent(seg));
- const encodedPath = pathSegments.join('/');
-
- // 如果有文件名列表,使用实际文件名;否则使用帧号构造文件名
- let imgSrc;
- if (fileNames[i]) {
- // 使用实际文件名
- imgSrc = `${TEXTURE_ROOT}/${encodedPath}/${encodeURIComponent(fileNames[i])}`;
- } else {
- // 回退到使用帧号构造文件名
- const frameName = frameNum.toString().padStart(2, '0');
- imgSrc = `${TEXTURE_ROOT}/${encodedPath}/${frameName}.png`;
- }
-
- const img = await new Promise((resolve, reject) => {
- const image = new Image();
- image.crossOrigin = 'anonymous';
- image.onload = () => resolve(image);
- image.onerror = () => reject(new Error(`Failed to load image: ${imgSrc}`));
- image.src = imgSrc;
- });
-
- images.push({
- img: img,
- width: img.width,
- height: img.height,
- frameNum: frameNum
- });
- }
-
- // 计算布局(简化版,使用简单的网格布局)
- const frameWidth = images[0].width;
- const frameHeight = images[0].height;
- const cols = Math.ceil(Math.sqrt(images.length));
- const rows = Math.ceil(images.length / cols);
-
- // 创建 Canvas 并绘制
- const canvas = document.createElement('canvas');
- canvas.width = frameWidth * cols;
- canvas.height = frameHeight * rows;
- const ctx = canvas.getContext('2d');
-
- // 保存 canvas 和布局信息用于下载
- this.spritesheetCanvas = canvas;
-
- // 填充透明背景
- ctx.clearRect(0, 0, canvas.width, canvas.height);
-
- // 保存布局信息(用于生成 JSON)
- const layout = [];
-
- // 绘制所有图片
- images.forEach((item, index) => {
- const col = index % cols;
- const row = Math.floor(index / cols);
- const x = col * frameWidth;
- const y = row * frameHeight;
- ctx.drawImage(item.img, x, y);
-
- // 保存布局信息
- layout.push({
- x: x,
- y: y,
- width: item.width,
- height: item.height,
- frameNum: item.frameNum
- });
- });
-
- // 保存布局信息
- this.spritesheetLayout = {
- layout: layout,
- sheetWidth: canvas.width,
- sheetHeight: canvas.height
- };
-
- // 转换为 base64
- const imageUrl = await new Promise((resolve) => {
- canvas.toBlob((blob) => {
- const url = URL.createObjectURL(blob);
- resolve(url);
- }, 'image/png');
- });
-
- // 保存原始 spritesheet 的 base64 数据
- this.originalSpritesheetData = await new Promise((resolve) => {
- canvas.toBlob((blob) => {
- const reader = new FileReader();
- reader.onload = () => resolve(reader.result);
- reader.readAsDataURL(blob);
- }, 'image/png');
- });
-
- // 显示预览图
- this.showPreview(imageUrl);
-
- // 如果已经有参考图,显示替换按钮
- if (this.referenceImageData && this.replaceBtn) {
- this.replaceBtn.style.display = 'block';
- }
-
- // 移除自动调用替换 API 的逻辑
- } catch (error) {
- // console.error('[ExportView] 生成预览图失败:', error);
- if (this.previewPlaceholder) {
- // 隐藏加载动画,显示错误信息
- const spinner = this.previewPlaceholder.querySelector('.loading-spinner');
- const loadingText = this.previewPlaceholder.querySelector('.loading-text');
- if (spinner) spinner.style.display = 'none';
- if (loadingText) {
- loadingText.textContent = '生成预览图失败: ' + error.message;
- loadingText.style.color = '#ef4444';
- }
- this.previewPlaceholder.classList.remove('hide');
- }
- }
- }
- /**
- * 计算宽高比
- * @param {number} width - 宽度
- * @param {number} height - 高度
- * @returns {string} 宽高比字符串(例如:16:9)
- */
- calculateAspectRatio(width, height) {
- // 计算最大公约数
- const gcd = (a, b) => b === 0 ? a : gcd(b, a % b);
- const divisor = gcd(width, height);
- const ratioWidth = width / divisor;
- const ratioHeight = height / divisor;
-
- // 如果比例太大,使用简化版本
- if (ratioWidth > 100 || ratioHeight > 100) {
- // 使用小数形式
- const ratio = width / height;
- return ratio.toFixed(2) + ':1';
- }
-
- return `${ratioWidth}:${ratioHeight}`;
- }
- /**
- * 加载参考图
- * @param {File} file - 图片文件
- */
- loadReferenceImage(file) {
- const reader = new FileReader();
- reader.onload = (e) => {
- this.referenceImageData = e.target.result;
- if (this.referenceImage) {
- this.referenceImage.src = e.target.result;
- }
- if (this.referenceImageWrapper) {
- this.referenceImageWrapper.style.display = 'flex';
- }
- if (this.referenceUploadArea) {
- this.referenceUploadArea.classList.add('hide');
- }
-
- // 显示替换按钮和提示词配置区域(如果已经有 spritesheet)
- if (this.originalSpritesheetData) {
- if (this.replaceBtn) {
- this.replaceBtn.style.display = 'block';
- }
- // 显示提示词配置区域
- const promptConfigSection = document.getElementById('promptConfigSection');
- if (promptConfigSection) {
- promptConfigSection.style.display = 'flex';
- }
- }
-
- // 移除自动调用替换 API 的逻辑
- };
- reader.readAsDataURL(file);
- }
- /**
- * 删除参考图
- */
- removeReferenceImage() {
- // 清空参考图数据
- this.referenceImageData = null;
- this.replacedImageData = null; // 同时清空替换后的图片
- // 隐藏参考图,显示上传区域
- if (this.referenceImageWrapper) {
- this.referenceImageWrapper.style.display = 'none';
- }
- if (this.referenceImage) {
- this.referenceImage.src = '';
- }
- if (this.referenceUploadArea) {
- this.referenceUploadArea.classList.remove('hide');
- }
- if (this.referenceInput) {
- this.referenceInput.value = '';
- }
- // 隐藏替换按钮和提示词配置区域
- if (this.replaceBtn) {
- this.replaceBtn.style.display = 'none';
- this.replaceBtn.disabled = false;
- }
- const promptConfigSection = document.getElementById('promptConfigSection');
- if (promptConfigSection) {
- promptConfigSection.style.display = 'none';
- }
- // 如果预览图是替换后的图片,恢复显示原始 spritesheet
- if (this.replacedImageData && this.originalSpritesheetData) {
- // 清空替换后的图片,恢复显示原始预览
- this.replacedImageData = null;
- // 重新显示原始 spritesheet
- if (this.spritesheetCanvas) {
- this.spritesheetCanvas.toBlob((blob) => {
- const url = URL.createObjectURL(blob);
- this.showPreview(url);
- }, 'image/png');
- }
- }
- }
- /**
- * 调用角色替换 API
- */
- async replaceCharacter() {
- if (!this.originalSpritesheetData || !this.referenceImageData) {
- alert('请先上传参考图和生成 Spritesheet');
- return;
- }
- // 禁用替换按钮和下载按钮
- if (this.replaceBtn) {
- this.replaceBtn.disabled = true;
- }
- if (this.confirmBtn) {
- this.confirmBtn.disabled = true;
- }
- try {
- // 显示加载状态
- if (this.previewPlaceholder) {
- const spinner = this.previewPlaceholder.querySelector('.loading-spinner');
- const loadingText = this.previewPlaceholder.querySelector('.loading-text');
- if (spinner) spinner.style.display = 'block';
- if (loadingText) {
- loadingText.textContent = '正在生成替换后的图片...';
- loadingText.style.color = '#6b7280';
- }
- this.previewPlaceholder.classList.remove('hide');
- }
- if (this.previewImage) {
- this.previewImage.classList.remove('show');
- }
- // 准备图片数据(移除 data:image/png;base64, 前缀)
- const image1Base64 = this.originalSpritesheetData.replace(/^data:image\/\w+;base64,/, '');
- const image2Base64 = this.referenceImageData.replace(/^data:image\/\w+;base64,/, '');
- // 获取 image1 的尺寸
- const image1Width = this.spritesheetLayout?.sheetWidth || 0;
- const image1Height = this.spritesheetLayout?.sheetHeight || 0;
-
- // 获取额外提示词
- const additionalPrompt = this.additionalPromptInput?.value || '';
- // 调用 API
- const response = await fetch('http://localhost:3000/api/replace-character', {
- method: 'POST',
- headers: {
- 'Content-Type': 'application/json'
- },
- body: JSON.stringify({
- image1: image1Base64,
- image2: image2Base64,
- image1Width: image1Width,
- image1Height: image1Height,
- additionalPrompt: additionalPrompt
- })
- });
- if (!response.ok) {
- const errorData = await response.json().catch(() => ({ error: 'Unknown error' }));
- throw new Error(errorData.error || `服务器错误: ${response.status}`);
- }
- const result = await response.json();
-
- if (result.success && result.imageData) {
- // Gemini 返回的图片 base64
- const geminiImageBase64 = result.imageData;
-
- // 调用抠图 API 处理图片
- if (this.previewPlaceholder) {
- const loadingText = this.previewPlaceholder.querySelector('.loading-text');
- if (loadingText) {
- loadingText.textContent = '正在抠图处理...';
- }
- }
-
- const mattingResponse = await fetch('http://localhost:3000/api/remove-background-base64', {
- method: 'POST',
- headers: {
- 'Content-Type': 'application/json'
- },
- body: JSON.stringify({
- imageBase64: geminiImageBase64
- })
- });
- if (!mattingResponse.ok) {
- const errorData = await mattingResponse.json().catch(() => ({ error: 'Unknown error' }));
- throw new Error(errorData.error || `抠图失败: ${mattingResponse.status}`);
- }
- const mattingResult = await mattingResponse.json();
-
- if (mattingResult.success && mattingResult.imageData) {
- // 保存抠图后的图片
- this.replacedImageData = `data:image/png;base64,${mattingResult.imageData}`;
-
- // 显示抠图后的图片
- this.showPreview(this.replacedImageData);
- } else {
- throw new Error('抠图处理失败');
- }
- } else {
- throw new Error('API 返回失败或未找到图片数据');
- }
- } catch (error) {
- // console.error('[ExportView] 替换角色失败:', error);
- if (this.previewPlaceholder) {
- const spinner = this.previewPlaceholder.querySelector('.loading-spinner');
- const loadingText = this.previewPlaceholder.querySelector('.loading-text');
- if (spinner) spinner.style.display = 'none';
- if (loadingText) {
- loadingText.textContent = '替换失败: ' + error.message;
- loadingText.style.color = '#ef4444';
- }
- this.previewPlaceholder.classList.remove('hide');
- }
- } finally {
- // 重新启用替换按钮和下载按钮
- if (this.replaceBtn) {
- this.replaceBtn.disabled = false;
- }
- if (this.confirmBtn) {
- this.confirmBtn.disabled = false;
- }
- }
- }
- /**
- * 显示预览图(Spritesheet)
- * @param {string} imageUrl - 图片URL或base64数据
- */
- showPreview(imageUrl) {
- if (!imageUrl) {
- // console.warn('[ExportView] 没有提供图片数据');
- return;
- }
- // console.log('[ExportView] 显示预览图');
-
- // 保存图片数据
- this.imageData = imageUrl;
-
- // 图片加载前禁用下载按钮
- if (this.confirmBtn) {
- this.confirmBtn.disabled = true;
- }
-
- // 加载图片
- const img = new Image();
- img.onload = () => {
- if (this.previewImage) {
- this.previewImage.src = imageUrl;
- this.previewImage.classList.add('show');
- }
- if (this.previewPlaceholder) {
- this.previewPlaceholder.classList.add('hide');
- }
- // 图片加载完成后启用下载按钮
- if (this.confirmBtn) {
- this.confirmBtn.disabled = false;
- }
- // console.log('[ExportView] ✓ 预览图已加载');
- };
-
- img.onerror = () => {
- // 图片加载失败时禁用下载按钮
- if (this.confirmBtn) {
- this.confirmBtn.disabled = true;
- }
- // console.error('[ExportView] 图片加载失败');
- if (this.previewPlaceholder) {
- // 隐藏加载动画,显示错误信息
- const spinner = this.previewPlaceholder.querySelector('.loading-spinner');
- const loadingText = this.previewPlaceholder.querySelector('.loading-text');
- if (spinner) spinner.style.display = 'none';
- if (loadingText) {
- loadingText.textContent = '图片加载失败';
- loadingText.style.color = '#ef4444';
- }
- this.previewPlaceholder.classList.remove('hide');
- }
- };
-
- img.src = imageUrl;
- }
- /**
- * 生成 JSON 数据
- * @param {string} folderName - 文件夹名称
- * @param {Array} layout - 布局信息数组
- * @param {number} sheetWidth - Spritesheet 宽度
- * @param {number} sheetHeight - Spritesheet 高度
- * @returns {string} JSON 字符串
- */
- generateJSON(folderName, layout, sheetWidth, sheetHeight) {
- const frames = {};
-
- layout.forEach((item, index) => {
- // 使用实际的帧号,确保与原始文件名一致
- const frameNum = item.frameNum ? item.frameNum.toString().padStart(2, '0') : (index + 1).toString().padStart(2, '0');
- const frameName = `${frameNum}.png`;
- const x = item.x;
- const y = item.y;
- const width = item.width;
- const height = item.height;
-
- // 标准的 TexturePacker JSON 格式,Cocos Creator 3.8 完全兼容
- frames[frameName] = {
- frame: {
- x: x,
- y: y,
- w: width,
- h: height
- },
- rotated: false,
- trimmed: false,
- spriteSourceSize: { x: 0, y: 0, w: width, h: height },
- sourceSize: { w: width, h: height }
- };
- });
- // Cocos Creator 3.8 兼容的 TexturePacker JSON 格式
- const json = {
- frames: frames,
- meta: {
- app: "https://www.codeandweb.com/texturepacker",
- version: "1.0",
- image: `${folderName}.png`,
- format: "RGBA8888",
- size: { w: sheetWidth, h: sheetHeight },
- scale: 1
- }
- };
- return JSON.stringify(json, null, 2);
- }
- /**
- * 将 Blob 转换为 Base64
- * @param {Blob} blob - Blob 对象
- * @returns {Promise<string>} Base64 字符串
- */
- blobToBase64(blob) {
- return new Promise((resolve, reject) => {
- const reader = new FileReader();
- reader.onloadend = () => {
- // 移除 data:image/png;base64, 前缀
- const base64 = reader.result.split(',')[1];
- resolve(base64);
- };
- reader.onerror = reject;
- reader.readAsDataURL(blob);
- });
- }
- /**
- * 下载文件
- * @param {Blob} data - 文件数据
- * @param {string} filename - 文件名
- * @param {string} mimeType - MIME 类型
- */
- downloadFile(data, filename, mimeType) {
- const blob = new Blob([data], { type: mimeType });
- const url = URL.createObjectURL(blob);
- const a = document.createElement('a');
- a.href = url;
- a.download = filename;
- document.body.appendChild(a);
- a.click();
- document.body.removeChild(a);
- URL.revokeObjectURL(url);
- }
- /**
- * 处理下载按钮点击
- */
- async handleConfirm() {
- // console.log('[ExportView] 用户点击下载按钮');
-
- if (!this.spritesheetCanvas || !this.spritesheetLayout) {
- // console.warn('[ExportView] 没有可下载的 Spritesheet');
- return;
- }
-
- try {
- // 生成 JSON 数据
- const folderName = this.folderName.split('/').pop() || 'spritesheet';
- const jsonData = this.generateJSON(
- folderName,
- this.spritesheetLayout.layout,
- this.spritesheetLayout.sheetWidth,
- this.spritesheetLayout.sheetHeight
- );
-
- // 确定使用哪个图片:如果有替换后的图片,使用替换后的;否则使用原始的
- let imageBase64;
- if (this.replacedImageData) {
- // 使用替换后的图片(移除 data:image/png;base64, 前缀)
- imageBase64 = this.replacedImageData.replace(/^data:image\/\w+;base64,/, '');
- } else {
- // 使用原始 spritesheet
- const imageBlob = await new Promise((resolve, reject) => {
- this.spritesheetCanvas.toBlob((blob) => {
- if (blob) {
- resolve(blob);
- } else {
- reject(new Error('Canvas 转换失败'));
- }
- }, 'image/png');
- });
-
- // 将图片转换为 Base64
- imageBase64 = await this.blobToBase64(imageBlob);
- }
-
- // 发送到服务器打包
- const response = await fetch('http://localhost:3000/api/pack', {
- method: 'POST',
- headers: {
- 'Content-Type': 'application/json'
- },
- body: JSON.stringify({
- folderName: folderName,
- imageData: imageBase64,
- jsonData: jsonData
- })
- });
- if (!response.ok) {
- const errorData = await response.json().catch(() => ({ error: 'Unknown error' }));
- throw new Error(errorData.error || `服务器错误: ${response.status}`);
- }
- // 获取 ZIP 文件的 Blob
- const zipBlob = await response.blob();
-
- // 下载 ZIP 文件
- this.downloadFile(zipBlob, `${folderName}.zip`, 'application/zip');
-
- // 关闭弹出框
- this.close();
- } catch (error) {
- // console.error('[ExportView] 下载失败:', error);
- alert(`下载失败: ${error.message}`);
- }
- }
- /**
- * 关闭弹出框
- */
- close() {
- // console.log('[ExportView] 关闭导出弹出框');
-
- // 清空所有数据
- this.reset();
-
- // 通知父窗口关闭弹出框
- if (window.parent && window.parent !== window) {
- window.parent.postMessage({
- type: 'close-export-view'
- }, '*');
- }
- }
- /**
- * 重置所有数据和UI状态
- */
- reset() {
- // 清空数据属性
- this.imageData = null;
- this.referenceImageData = null;
- this.spritesheetCanvas = null;
- this.folderName = null;
- this.spritesheetLayout = null;
- this.replacedImageData = null;
- this.originalSpritesheetData = null;
- // 重置参考图区域
- if (this.referenceImageWrapper) {
- this.referenceImageWrapper.style.display = 'none';
- }
- if (this.referenceImage) {
- this.referenceImage.src = '';
- }
- if (this.referenceUploadArea) {
- this.referenceUploadArea.classList.remove('hide');
- }
- if (this.referenceInput) {
- this.referenceInput.value = '';
- }
- if (this.replaceBtn) {
- this.replaceBtn.style.display = 'none';
- this.replaceBtn.disabled = false;
- }
- // 重置预览图区域
- if (this.previewImage) {
- this.previewImage.src = '';
- this.previewImage.classList.remove('show');
- }
- if (this.previewPlaceholder) {
- const spinner = this.previewPlaceholder.querySelector('.loading-spinner');
- const loadingText = this.previewPlaceholder.querySelector('.loading-text');
- if (spinner) spinner.style.display = 'block';
- if (loadingText) {
- loadingText.textContent = '正在生成预览图...';
- loadingText.style.color = '#6b7280';
- }
- this.previewPlaceholder.classList.remove('hide');
- }
- // 重置提示词配置区域
- const promptConfigSection = document.getElementById('promptConfigSection');
- if (promptConfigSection) {
- promptConfigSection.style.display = 'none';
- }
- if (this.additionalPromptInput) {
- this.additionalPromptInput.value = '';
- }
- // 重置按钮状态
- if (this.confirmBtn) {
- this.confirmBtn.disabled = true;
- }
- }
- }
- // 初始化
- window.ExportView = new ExportView();
|