好友
阅读权限20
听众
最后登录1970-1-1
|
午夜飘雪
发表于 2025-12-4 02:46
本帖最后由 午夜飘雪 于 2026-11-3 23:51 编辑
图片转图标ICO v1.0.1本地运行安全可靠
一、软件介绍
1.1 这是什么
一个把图片转成图标的网页工具。上传一张图,选形状、调裁剪、点下载,得到可以直接用的 **PNG / ICO / SVG** 图标。
不是"改个扩展名"的假导出:ICO 是真正按微软 ICO 规范编码的多尺寸文件,SVG 剪影模式下是真正的矢量路径。
1.2 形态与技术
| 文件形态 | **单个 `.html` 文件**,约 93 KB,无外部依赖 |
| 运行方式 | 浏览器直接打开,双击即用 |
| 是否联网 | **完全离线**。无 CDN、无第三方库、无网络请求 |
| 图片是否上传 | **不上传**。所有计算在浏览器本地完成,图片不离开本机 |
| 浏览器要求 | Chrome / Edge / Firefox 等现代浏览器 |
| 系统要求 | 无。Windows / macOS / Linux 均可 |
图片转图标成品下载
文字图片转图标.txt
(117 Bytes, 下载次数: 7)
文字转图标增强版 - 文字转图标 ICO(安全免费)
https://www.52pojie.cn/thread-2076927-1-1.html
(出处: 吾爱破解论坛)
更新说明
三、更新说明
v1.0.1(2026-11-03)· 布局优化定稿
> 本版把上一轮之后的所有改动(自动识别框即范围、拖拽上传、删预览图、布局重排、新增 3 种形状)
| **修复:自动识别错位
| **修复:框动不重识别
| **修复:框选决定主体
| **新增:拖拽上传
| **精简:删掉上传预览图
| **修复:框形同虚设
| **新增:框下状态行
| **简化:删掉裁剪模式
| **收纳:滑块折叠
| **形状:删心形补盾牌
| **样式:统一外框
| **防御:几何 NaN
| **布局:按钮重排
| **布局:合并面板
| **布局:形状固定网格
| **新增:3 种形状 | 水滴 / 云朵 / 闪电
| **修复:重置后滑块不回位
代码拿走不谢
[HTML] 纯文本查看 复制代码 <!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>图标生成器 - 文字/图片转PNG/ICO/SVG</title>
<style>
/* 保持原有样式不变 */
* { margin: 0; padding: 0; box-sizing: border-box; font-family: 'Segoe UI', sans-serif; }
body { background: linear-gradient(135deg, #f5f7fa 0%, #c3cfe2 100%); color: #333; min-height: 100vh; padding: 10px; }
.container { max-width: 1200px; margin: 0 auto; background: white; border-radius: 15px; box-shadow: 0 10px 30px rgba(0,0,0,0.1); overflow: hidden; }
header { background: linear-gradient(90deg, #4b6cb7 0%, #182848 100%); color: white; padding: 20px 30px; text-align: center; }
header h1 { font-size: 1.8rem; margin-bottom: 8px; }
.app-content { display: flex; flex-wrap: wrap; padding: 20px; }
.controls, .preview { flex: 1; min-width: 300px; padding: 20px; }
.controls { border-right: 1px solid #eee; max-height: calc(100vh - 150px); overflow-y: auto; }
.preview { display: flex; flex-direction: column; align-items: center; gap: 20px; }
.control-group { margin-bottom: 20px; padding: 15px; background: #f8f9fa; border-radius: 10px; box-shadow: 0 2px 5px rgba(0,0,0,0.05); }
.control-group h3 { margin-bottom: 12px; color: #4b6cb7; border-bottom: 1px solid #eaeaea; padding-bottom: 8px; }
.form-group { margin-bottom: 15px; }
label { display: block; margin-bottom: 5px; font-weight: 500; }
input, select, button, textarea { width: 100%; padding: 10px 15px; border: 1px solid #ddd; border-radius: 5px; font-size: 1rem; }
textarea { resize: vertical; min-height: 80px; line-height: 1.4; }
button { background: linear-gradient(90deg, #4b6cb7 0%, #182848 100%); color: white; border: none; cursor: pointer; font-weight: 600; transition: all 0.3s ease; margin-top: 10px; }
button:hover { transform: translateY(-2px); box-shadow: 0 5px 15px rgba(0,0,0,0.1); }
#uploadFontBtn { background: linear-gradient(90deg, #e67e22 0%, #d35400 100%); }
.color-input { display: flex; align-items: center; }
.color-input input { flex: 1; }
.color-preview { width: 30px; height: 30px; border-radius: 5px; margin-left: 10px; border: 1px solid #ddd; }
.shape-options, .size-options { display: flex; flex-wrap: wrap; gap: 10px; }
.position-options { display: grid; grid-template-columns: repeat(3, 1fr); gap: 8px; width: 100%; }
.shape-option, .size-option { flex: 1; min-width: 80px; text-align: center; padding: 10px; border: 2px solid #ddd; border-radius: 5px; cursor: pointer; transition: all 0.2s; }
.position-option { padding: 12px 5px; font-size: 0.9rem; border: 2px solid #ddd; border-radius: 5px; cursor: pointer; transition: all 0.2s; text-align: center; background: #f8f9fa; }
.shape-option:hover, .size-option:hover, .position-option:hover { border-color: #4b6cb7; }
.shape-option.active, .size-option.active, .position-option.active { border-color: #4b6cb7; background: rgba(75,108,183,0.1); }
.checkbox-group { display: flex; align-items: center; margin-bottom: 10px; }
.checkbox-group input { width: auto; margin-right: 10px; }
#transparentBgGroup { padding: 8px; background: rgba(75,108,183,0.05); border-radius: 5px; margin-top: 5px; }
.char-count { font-size: 0.8rem; color: #666; margin-top: 5px; }
.max-chars { color: #e74c3c; }
.stretch-controls, .font-size-controls { display: flex; gap: 15px; margin-top: 10px; }
.stretch-control, .font-size-control { flex: 1; text-align: center; }
.stretch-control label, .font-size-control label { font-size: 0.9rem; margin-bottom: 5px; }
.font-size-note, .stretch-note { font-size: 0.8rem; color: #e67e22; margin-top: 5px; padding: 5px; background: rgba(230,126,34,0.05); border-radius: 4px; }
.stretch-value, .font-size-value { font-size: 0.8rem; color: #666; margin-top: 5px; }
.preview-area { width: 256px; height: 256px; border: 1px solid #ddd; border-radius: 10px; display: flex; align-items: center; justify-content: center; overflow: hidden; background: linear-gradient(45deg, #f0f0f0 25%, transparent 25%), linear-gradient(-45deg, #f0f0f0 25%, transparent 25%), linear-gradient(45deg, transparent 75%, #f0f0f0 75%), linear-gradient(-45deg, transparent 75%, #f0f0f0 75%); background-size: 20px 20px; background-position: 0 0, 0 10px, 10px -10px, -10px 0px; box-shadow: 0 5px 15px rgba(0,0,0,0.05); transition: all 0.1s ease; }
canvas { max-width: 100%; max-height: 100%; }
.download-options { display: flex; gap: 10px; width: 100%; max-width: 400px; }
.download-options button { flex: 1; }
.size-preview { display: flex; flex-wrap: wrap; gap: 10px; justify-content: center; width: 100%; max-width: 400px; }
.size-preview-item { display: flex; flex-direction: column; align-items: center; margin-bottom: 10px; }
.size-preview-canvas { border: 1px solid #ddd; margin-bottom: 5px; background: linear-gradient(45deg, #f0f0f0 25%, transparent 25%), linear-gradient(-45deg, #f0f0f0 25%, transparent 25%), linear-gradient(45deg, transparent 75%, #f0f0f0 75%), linear-gradient(-45deg, transparent 75%, #f0f0f0 75%); background-size: 8px 8px; background-position: 0 0, 0 4px, 4px -4px, -4px 0px; }
footer { text-align: center; padding: 15px; color: #666; font-size: 0.9rem; border-top: 1px solid #eee; }
.font-upload-area, .image-upload-area { margin: 15px 0; padding: 15px; border: 2px dashed #e67e22; border-radius: 5px; text-align: center; transition: all 0.3s; }
.image-upload-area { border-color: #3498db; }
.font-upload-area:hover, .image-upload-area:hover { background: rgba(230,126,34,0.05); }
.image-upload-area:hover { background: rgba(52,152,219,0.05); }
#fontFileInput, #imageFileInput { display: none; }
.upload-hint { font-size: 0.85rem; color: #666; margin-top: 8px; }
.upload-success { margin-top: 10px; padding: 8px; background: rgba(46,204,113,0.1); color: #27ae60; border-radius: 4px; font-size: 0.9rem; display: none; }
.progress-modal { position: fixed; top: 0; left: 0; width: 100%; height: 100%; background: rgba(0,0,0,0.5); display: flex; flex-direction: column; align-items: center; justify-content: center; z-index: 1000; opacity: 0; visibility: hidden; transition: all 0.3s ease; }
.progress-modal.active { opacity: 1; visibility: visible; }
.progress-container { background: white; padding: 20px; border-radius: 10px; width: 90%; max-width: 500px; box-shadow: 0 10px 30px rgba(0,0,0,0.2); }
.progress-title { font-size: 1.1rem; font-weight: 600; color: #333; margin-bottom: 15px; text-align: center; }
.progress-bar-container { width: 100%; height: 12px; background: #f1f1f1; border-radius: 6px; overflow: hidden; margin-bottom: 15px; }
.progress-bar { height: 100%; background: linear-gradient(90deg, #4b6cb7 0%, #182848 100%); width: 0%; border-radius: 6px; transition: width 0.5s ease; }
.progress-text { font-size: 0.9rem; color: #666; text-align: center; }
.progress-success { color: #27ae60; font-weight: 600; display: none; }
.manual-wrap-hint { font-size: 0.8rem; color: #666; margin-top: 5px; padding: 5px; background: rgba(52,152,219,0.05); border-radius: 4px; display: none; }
.manual-wrap-hint.active { display: block; }
/* 新增样式 */
.tab-container { display: flex; margin-bottom: 20px; border-radius: 8px; overflow: hidden; border: 1px solid #ddd; }
.tab-button { flex: 1; padding: 12px; text-align: center; background: #f8f9fa; border: none; cursor: pointer; transition: all 0.2s; font-weight: 600; color: #666; margin-top: 0; }
.tab-button.active { background: linear-gradient(90deg, #4b6cb7 0%, #182848 100%); color: white; }
.tab-content { display: none; }
.tab-content.active { display: block; }
.image-preview-container { width: 100%; height: 150px; border: 1px solid #ddd; border-radius: 8px; margin-top: 10px; display: flex; align-items: center; justify-content: center; overflow: hidden; background: #f8f9fa; }
#uploadedImagePreview { max-width: 100%; max-height: 100%; display: none; }
.image-processing-options { margin-top: 15px; padding: 10px; background: rgba(52,152,219,0.05); border-radius: 5px; }
.image-clear-btn { background: linear-gradient(90deg, #e74c3c 0%, #c0392b 100%); margin-top: 10px; }
@media (max-width: 768px) {
.app-content { flex-direction: column; }
.controls { border-right: none; border-bottom: 1px solid #eee; max-height: none; }
.preview { min-height: 500px; justify-content: flex-start; padding-top: 30px; }
.stretch-controls, .font-size-controls { flex-direction: column; }
.download-options { flex-direction: column; max-width: 100%; }
}
</style>
</head>
<body>
<div class="container">
<header>
<h1>图标生成器 - 文字/图片转PNG/ICO/SVG (增强版)</h1>
</header>
<div class="app-content">
<div class="controls">
<!-- 新增标签页切换 -->
<div class="tab-container">
<button class="tab-button active" data-tab="text-tab">文字生成</button>
<button class="tab-button" data-tab="image-tab">图片转换</button>
</div>
<!-- 文字生成标签内容 -->
<div class="tab-content active" id="text-tab">
<div class="control-group">
<h3>文字设置</h3>
<div class="form-group">
<label for="textInput">输入文字或Emoji(≤20个字符,支持换行)</label>
<textarea id="textInput" maxlength="20" placeholder="可输入文字/Emoji,按Enter换行">图标</textarea>
<div class="char-count">当前字符数: <span id="charCount">2</span>/20</div>
<div class="manual-wrap-hint" id="manualWrapHint">✏️ 手动换行已启用:按Enter键换行</div>
</div>
<div class="form-group">
<label for="fontSelect">选择字体(内置+上传)</label>
<select id="fontSelect" size="8" style="height: 200px; overflow-y: auto;">
<!-- 字体选项通过JS动态填充 -->
</select>
</div>
<div class="font-upload-area">
<label for="fontFileInput" style="cursor: pointer; font-weight: 600; color: #e67e22;">点击选择本地字体文件(TTF/OTF)</label>
<input type="file" id="fontFileInput" accept=".ttf,.otf,.ttc" multiple>
<p class="upload-hint">支持格式:TTF/OTF/TTC | 可批量上传 | 仅临时使用</p>
<div id="uploadSuccessMsg" class="upload-success">✅ 字体上传成功!已添加到字体列表末尾</div>
</div>
<div class="stretch-controls">
<div class="stretch-control">
<label for="colorInput">文字颜色</label>
<div class="color-input">
<input type="color" id="colorInput" value="#ea1026">
<div class="color-preview" id="colorPreview"></div>
</div>
</div>
<div class="stretch-control">
<label for="bgColorInput">背景颜色</label>
<div class="color-input">
<input type="color" id="bgColorInput" value="#ffffff">
<div class="color-preview" id="bgColorPreview"></div>
</div>
</div>
</div>
<div class="checkbox-group" id="transparentBgGroup">
<input type="checkbox" id="transparentBg" checked>
<label for="transparentBg">启用透明背景(取消则显示上方背景色)</label>
</div>
<div class="checkbox-group">
<input type="checkbox" id="autoWrap" checked>
<label for="autoWrap">自动换行(长文本自动拆分)</label>
</div>
<div class="checkbox-group">
<input type="checkbox" id="textCenter" checked>
<label for="textCenter">文字居中对齐(换行后仍居中)</label>
</div>
<div class="checkbox-group">
<input type="checkbox" id="autoStretch" checked>
<label for="autoStretch">自动拉伸文字以适应图标</label>
</div>
<div class="checkbox-group">
<input type="checkbox" id="stretchFollowFont" checked>
<label for="stretchFollowFont">拉伸比例随字体大小联动(取消则独立控制)</label>
</div>
<div class="font-size-controls">
<div class="font-size-control">
<label for="fontSizeSlider">字体基础大小(%)</label>
<input type="range" id="fontSizeSlider" min="10" max="200" value="80" disabled>
<div class="font-size-value" id="fontSizeValue">80%</div>
<div class="font-size-note">✏️ 提示:需先关闭"自动拉伸"才能手动调整</div>
</div>
</div>
<div class="control-group" style="margin-top: 15px;">
<h3>文字拉伸控制(实时预览)</h3>
<div class="stretch-controls">
<div class="stretch-control">
<label for="horizontalStretch">水平拉伸比例(%)</label>
<input type="range" id="horizontalStretch" min="20" max="800" value="141">
<div class="stretch-value" id="horizontalValue">141%</div>
<div class="stretch-note">↔️ 单独控制左右拉伸,100%为默认</div>
</div>
<div class="stretch-control">
<label for="verticalStretch">垂直拉伸比例(%)</label>
<input type="range" id="verticalStretch" min="20" max="800" value="126">
<div class="stretch-value" id="verticalValue">126%</div>
<div class="stretch-note">↕️ 单独控制上下拉伸,100%为默认</div>
</div>
</div>
<div class="stretch-controls" style="margin-top: 15px;">
<div class="stretch-control">
<label for="horizontalOffset">横向偏移(px)</label>
<input type="range" id="horizontalOffset" min="-50" max="50" value="0">
<div class="stretch-value" id="horizontalOffsetValue">0px</div>
</div>
<div class="stretch-control">
<label for="verticalOffset">垂直偏移(px)</label>
<input type="range" id="verticalOffset" min="-50" max="50" value="0">
<div class="stretch-value" id="verticalOffsetValue">0px</div>
</div>
</div>
<!-- SVG垂直偏移校正控制 -->
<div class="stretch-controls" style="margin-top: 15px;">
<div class="stretch-control">
<label for="svgVerticalAdjust">SVG垂直校正(px)</label>
<input type="range" id="svgVerticalAdjust" min="-50" max="50" value="10">
<div class="stretch-value" id="svgVerticalAdjustValue">10px</div>
<div class="stretch-note">🔧 专门校正SVG文字垂直偏移</div>
</div>
<div class="stretch-control">
<label for="svgHorizontalAdjust">SVG水平校正(px)</label>
<input type="range" id="svgHorizontalAdjust" min="-50" max="50" value="0">
<div class="stretch-value" id="svgHorizontalAdjustValue">0px</div>
<div class="stretch-note">🔧 专门校正SVG文字水平偏移</div>
</div>
</div>
</div>
<div class="form-group" style="margin-top: 20px;">
<label>文字位置(九宫格)</label>
<div class="position-options">
<div class="position-option" data-position="top-left">左上</div>
<div class="position-option" data-position="top-center">中上</div>
<div class="position-option" data-position="top-right">右上</div>
<div class="position-option" data-position="center-left">左中</div>
<div class="position-option active" data-position="center-center">居中</div>
<div class="position-option" data-position="center-right">右中</div>
<div class="position-option" data-position="bottom-left">左下</div>
<div class="position-option" data-position="bottom-center">中下</div>
<div class="position-option" data-position="bottom-right">右下</div>
</div>
</div>
<h3>图标形状</h3>
<div class="shape-options">
<div class="shape-option" data-shape="square">方形</div>
<div class="shape-option" data-shape="circle">圆形</div>
<div class="shape-option active" data-shape="rounded">圆角方形</div>
</div>
</div>
</div>
<!-- 图片转换标签内容 -->
<div class="tab-content" id="image-tab">
<div class="control-group">
<h3>图片上传</h3>
<div class="image-upload-area">
<label for="imageFileInput" style="cursor: pointer; font-weight: 600; color: #3498db;">点击选择图片文件(PNG/JPG/GIF/WebP)</label>
<input type="file" id="imageFileInput" accept="image/png,image/jpeg,image/gif,image/webp">
<p class="upload-hint">支持格式:PNG/JPG/GIF/WebP | 建议尺寸:256×256px | 支持透明背景</p>
<div id="imageUploadSuccessMsg" class="upload-success">✅ 图片上传成功!</div>
</div>
<div class="image-preview-container">
<img id="uploadedImagePreview" src="" alt="图片预览">
<span id="noImageText">暂无图片,请上传...</span>
</div>
<button id="clearImageBtn" class="image-clear-btn" style="display: none;">清空图片</button>
<div class="image-processing-options">
<h4 style="margin-bottom: 10px; color: #3498db;">图片处理选项</h4>
<div class="checkbox-group">
<input type="checkbox" id="imageKeepAspectRatio" checked>
<label for="imageKeepAspectRatio">保持图片比例(不拉伸)</label>
</div>
<div class="checkbox-group">
<input type="checkbox" id="imageAutoCrop" checked>
<label for="imageAutoCrop">自动裁剪(居中裁剪到正方形)</label>
</div>
<div class="checkbox-group">
<input type="checkbox" id="imageTransparentBg" checked>
<label for="imageTransparentBg">保留透明背景(PNG/SVG)</label>
</div>
</div>
<h3>图标形状</h3>
<div class="shape-options">
<div class="shape-option" data-shape="square">方形</div>
<div class="shape-option" data-shape="circle">圆形</div>
<div class="shape-option active" data-shape="rounded">圆角方形</div>
</div>
</div>
</div>
</div>
<div class="preview">
<div class="preview-area">
<canvas id="previewCanvas" width="256" height="256"></canvas>
</div>
<div class="control-group">
<h3>图标尺寸</h3>
<div class="size-options">
<div class="size-option" data-size="16">16×16</div>
<div class="size-option" data-size="32">32×32</div>
<div class="size-option" data-size="48">48×48</div>
<div class="size-option" data-size="64">64×64</div>
<div class="size-option" data-size="128">128×128</div>
<div class="size-option active" data-size="256">256×256</div>
</div>
</div>
<div class="download-options">
<button id="downloadPngBtn">下载PNG</button>
<button id="downloadIcoBtn">下载ICO</button>
<button id="downloadSvgBtn">下载SVG</button>
</div>
<div class="size-preview">
<!-- 尺寸预览区域通过JS动态生成 -->
</div>
</div>
</div>
<footer>
<p>图标生成器 © 2025 - 支持PNG、ICO和SVG格式输出 | 增强版:文字/图片转换,SVG字体精准适配</p>
</footer>
</div>
<div class="progress-modal" id="downloadProgressModal">
<div class="progress-container">
<div class="progress-title" id="progressTitle">正在准备下载...</div>
<div class="progress-bar-container">
<div class="progress-bar" id="progressBar"></div>
</div>
<div class="progress-text">
<span id="progressPercent">0%</span> | <span id="progressStep">初始化...</span>
<span id="progressSuccess" class="progress-success">下载准备完成!</span>
</div>
</div>
</div>
<script>
document.addEventListener('DOMContentLoaded', function() {
// DOM元素获取
const textInput = document.getElementById('textInput');
const charCount = document.getElementById('charCount');
const manualWrapHint = document.getElementById('manualWrapHint');
const autoWrap = document.getElementById('autoWrap');
const textCenter = document.getElementById('textCenter');
const autoStretch = document.getElementById('autoStretch');
const stretchFollowFont = document.getElementById('stretchFollowFont');
const fontSizeSlider = document.getElementById('fontSizeSlider');
const fontSizeValue = document.getElementById('fontSizeValue');
const horizontalStretch = document.getElementById('horizontalStretch');
const verticalStretch = document.getElementById('verticalStretch');
const horizontalOffset = document.getElementById('horizontalOffset');
const verticalOffset = document.getElementById('verticalOffset');
const svgVerticalAdjust = document.getElementById('svgVerticalAdjust');
const svgHorizontalAdjust = document.getElementById('svgHorizontalAdjust');
const horizontalValue = document.getElementById('horizontalValue');
const verticalValue = document.getElementById('verticalValue');
const horizontalOffsetValue = document.getElementById('horizontalOffsetValue');
const verticalOffsetValue = document.getElementById('verticalOffsetValue');
const svgVerticalAdjustValue = document.getElementById('svgVerticalAdjustValue');
const svgHorizontalAdjustValue = document.getElementById('svgHorizontalAdjustValue');
const fontSelect = document.getElementById('fontSelect');
const fontFileInput = document.getElementById('fontFileInput');
const uploadSuccessMsg = document.getElementById('uploadSuccessMsg');
const colorInput = document.getElementById('colorInput');
const colorPreview = document.getElementById('colorPreview');
const bgColorInput = document.getElementById('bgColorInput');
const bgColorPreview = document.getElementById('bgColorPreview');
const transparentBg = document.getElementById('transparentBg');
const shapeOptions = document.querySelectorAll('.shape-option');
const sizeOptions = document.querySelectorAll('.size-option');
const positionOptions = document.querySelectorAll('.position-option');
const downloadPngBtn = document.getElementById('downloadPngBtn');
const downloadIcoBtn = document.getElementById('downloadIcoBtn');
const downloadSvgBtn = document.getElementById('downloadSvgBtn');
const previewCanvas = document.getElementById('previewCanvas');
const sizePreview = document.querySelector('.size-preview');
const progressModal = document.getElementById('downloadProgressModal');
const progressTitle = document.getElementById('progressTitle');
const progressBar = document.getElementById('progressBar');
const progressPercent = document.getElementById('progressPercent');
const progressStep = document.getElementById('progressStep');
const progressSuccess = document.getElementById('progressSuccess');
// 新增图片相关元素
const tabButtons = document.querySelectorAll('.tab-button');
const tabContents = document.querySelectorAll('.tab-content');
const imageFileInput = document.getElementById('imageFileInput');
const uploadedImagePreview = document.getElementById('uploadedImagePreview');
const noImageText = document.getElementById('noImageText');
const imageUploadSuccessMsg = document.getElementById('imageUploadSuccessMsg');
const clearImageBtn = document.getElementById('clearImageBtn');
const imageKeepAspectRatio = document.getElementById('imageKeepAspectRatio');
const imageAutoCrop = document.getElementById('imageAutoCrop');
const imageTransparentBg = document.getElementById('imageTransparentBg');
// 全局变量
let selectedShape = 'rounded';
let selectedSize = 256;
let selectedPosition = 'center-center';
let ctx = previewCanvas.getContext('2d');
let uploadedFonts = new Map(); // key: 字体唯一名称, value: { face: FontFace, url: ObjectURL, dataUrl: 字体DataURL, fileName: 文件名 }
let fontCounter = 1;
const baseStretch = {
horizontal: 141,
vertical: 126
};
// 新增图片相关变量
let currentTab = 'text-tab';
let uploadedImage = null;
let imageObjectURL = null;
// 扩充后的内置字体库
const builtInFonts = [
{ group: '常用中文字体', fonts: [
{ family: 'Microsoft YaHei', name: '微软雅黑' },
{ family: '微软雅黑 Light', name: '微软雅黑 Light' },
{ family: 'SimSun', name: '宋体', selected: true },
{ family: '新宋体', name: '新宋体' },
{ family: 'FangSong', name: '仿宋' },
{ family: 'KaiTi', name: '楷体' },
{ family: 'LiSu', name: '隶书' },
{ family: 'YouYuan', name: '幼圆' },
{ family: '黑体', name: '黑体' },
{ family: '等线', name: '等线' },
{ family: '等线 Light', name: '等线 Light' },
{ family: 'STSong', name: '华文宋体' },
{ family: 'STHeiti', name: '华文黑体' },
{ family: 'STKaiti', name: '华文楷体' },
{ family: 'STFangsong', name: '华文仿宋' }
]},
{ group: '思源字体', fonts: [
{ family: "'Noto Sans SC', sans-serif", name: '思源黑体 (Noto Sans SC)' },
{ family: "'Noto Serif SC', serif", name: '思源宋体 (Noto Serif SC)' },
{ family: "'Noto Sans TC', sans-serif", name: '思源黑体 繁体 (Noto Sans TC)' },
{ family: "'Noto Serif TC', serif", name: '思源宋体 繁体 (Noto Serif TC)' }
]},
{ group: '华文字体', fonts: [
{ family: '华文中宋', name: '华文中宋' },
{ family: '华文仿宋', name: '华文仿宋' },
{ family: '华文宋体', name: '华文宋体' },
{ family: '华文彩云', name: '华文彩云' },
{ family: '华文新魏', name: '华文新魏' },
{ family: '华文楷体', name: '华文楷体' },
{ family: '华文琥珀', name: '华文琥珀' },
{ family: '华文细黑', name: '华文细黑' },
{ family: '华文行楷', name: '华文行楷' },
{ family: '华文隶书', name: '华文隶书' },
{ family: '华文圆体', name: '华文圆体' }
]},
{ group: '方正字体', fonts: [
{ family: '方正姚体', name: '方正姚体' },
{ family: '方正舒体', name: '方正舒体' },
{ family: '方正粗圆简体', name: '方正粗圆简体' },
{ family: '方正细圆简体', name: '方正细圆简体' },
{ family: '方正准圆简体', name: '方正准圆简体' },
{ family: '方正黑体简体', name: '方正黑体简体' }
]},
{ group: '经典宋体', fonts: [
{ family: 'SimSun-ExtB', name: '宋体-ExtB' },
{ family: 'NSimSun', name: '新宋体' },
{ family: 'SimHei', name: '黑体' },
{ family: 'PMingLiU', name: '细明体' },
{ family: 'MingLiU', name: '明体' }
]},
{ group: '英文字体', fonts: [
{ family: 'Arial', name: 'Arial' },
{ family: 'Arial Black', name: 'Arial Black' },
{ family: 'Verdana', name: 'Verdana' },
{ family: 'Helvetica', name: 'Helvetica' },
{ family: 'Georgia', name: 'Georgia' },
{ family: 'Times New Roman', name: 'Times New Roman' },
{ family: 'Courier New', name: 'Courier New' },
{ family: 'Impact', name: 'Impact' },
{ family: 'Comic Sans MS', name: 'Comic Sans MS' },
{ family: 'Tahoma', name: 'Tahoma' },
{ family: 'Trebuchet MS', name: 'Trebuchet MS' },
{ family: 'Palatino Linotype', name: 'Palatino Linotype' },
{ family: 'Book Antiqua', name: 'Book Antiqua' },
{ family: 'Arial Narrow', name: 'Arial Narrow' }
]},
{ group: '设计字体', fonts: [
{ family: 'Baskerville Old Face', name: 'Baskerville Old Face' },
{ family: 'Brush Script MT', name: 'Brush Script MT' },
{ family: 'Calibri', name: 'Calibri' },
{ family: 'Cambria', name: 'Cambria' },
{ family: 'Century Gothic', name: 'Century Gothic' },
{ family: 'Garamond', name: 'Garamond' },
{ family: 'Lucida Console', name: 'Lucida Console' },
{ family: 'Lucida Sans Unicode', name: 'Lucida Sans Unicode' },
{ family: 'Microsoft Sans Serif', name: 'Microsoft Sans Serif' },
{ family: 'Palatino', name: 'Palatino' },
{ family: 'Segoe UI', name: 'Segoe UI' },
{ family: 'Segoe Print', name: 'Segoe Print' }
]}
];
// 初始化字体选择框
function initFontSelect() {
fontSelect.innerHTML = '';
builtInFonts.forEach(group => {
const groupOption = document.createElement('option');
groupOption.disabled = true;
groupOption.innerHTML = `📁 ${group.group}`;
groupOption.className = 'font-group';
fontSelect.appendChild(groupOption);
group.fonts.forEach(font => {
const option = document.createElement('option');
option.value = font.family;
option.textContent = ` ${font.name}`;
option.dataset.aliases = JSON.stringify([font.family]);
if (font.selected) {
option.selected = true;
}
fontSelect.appendChild(option);
});
});
const uploadDivider = document.createElement('option');
uploadDivider.disabled = true;
uploadDivider.textContent = '────────── 本地上传字体(临时使用) ──────────';
fontSelect.appendChild(uploadDivider);
}
initFontSelect();
// 进度条控制
function initProgressBar(format, fileName) {
progressModal.classList.add('active');
progressTitle.textContent = `正在准备下载 ${format} 文件:${fileName}`;
progressBar.style.width = '0%';
progressPercent.textContent = '0%';
progressSuccess.style.display = 'none';
progressStep.textContent = '初始化...';
let currentProgress = 0;
const progressInterval = setInterval(() => {
currentProgress += 5;
if (currentProgress > 100) currentProgress = 100;
progressBar.style.width = `${currentProgress}%`;
progressPercent.textContent = `${currentProgress}%`;
const steps = ['初始化参数', '渲染图标', '优化质量', '处理数据', '生成链接', '完成'];
const stepIndex = Math.min(Math.floor(currentProgress / 20), steps.length - 1);
progressStep.textContent = steps[stepIndex];
if (currentProgress >= 100) clearInterval(progressInterval);
}, 100);
}
function closeProgressBar() {
progressStep.textContent = '文件生成完成!';
progressSuccess.style.display = 'inline-block';
setTimeout(() => {
progressModal.classList.remove('active');
setTimeout(() => {
progressSuccess.style.display = 'none';
progressBar.style.width = '0%';
}, 300);
}, 800);
}
// 下载功能:获取自定义文件名
function getCustomFileName(format) {
if (currentTab === 'text-tab') {
let content = textInput.value.trim() || '图标';
content = content.split('\n')[0].replace(/[\\/:*?"<>|]/g, '-');
return `${content.length > 10 ? content.substring(0,10)+'...' : content}-${selectedSize}.${format}`;
} else {
if (uploadedImage) {
let name = uploadedImage.name.replace(/\.[^/.]+$/, "").replace(/[\\/:*?"<>|]/g, '-');
return `${name}-${selectedSize}.${format}`;
}
return `image-icon-${selectedSize}.${format}`;
}
}
// 绘制图片图标
function drawImageIcon(canvas, size) {
if (!uploadedImage) return;
const ctx = canvas.getContext('2d');
ctx.clearRect(0, 0, size, size);
// 绘制背景
if (!imageTransparentBg.checked) {
ctx.fillStyle = '#ffffff';
if (selectedShape === 'circle') {
ctx.beginPath();
ctx.arc(size/2, size/2, size/2, 0, Math.PI * 2);
ctx.fill();
} else if (selectedShape === 'rounded') {
const radius = size * 0.1;
ctx.beginPath();
ctx.moveTo(radius, 0);
ctx.lineTo(size - radius, 0);
ctx.arcTo(size, 0, size, radius, radius);
ctx.lineTo(size, size - radius);
ctx.arcTo(size, size, size - radius, size, radius);
ctx.lineTo(radius, size);
ctx.arcTo(0, size, 0, size - radius, radius);
ctx.lineTo(0, radius);
ctx.arcTo(0, 0, radius, 0, radius);
ctx.closePath();
ctx.fill();
} else {
ctx.fillRect(0, 0, size, size);
}
}
// 创建临时图片对象
const img = new Image();
img.onload = function() {
// 根据选项处理图片
let drawWidth = size;
let drawHeight = size;
let offsetX = 0;
let offsetY = 0;
if (imageKeepAspectRatio.checked) {
const aspectRatio = img.width / img.height;
if (imageAutoCrop.checked) {
// 裁剪模式
let sourceX = 0;
let sourceY = 0;
let sourceWidth = img.width;
let sourceHeight = img.height;
if (aspectRatio > 1) {
// 宽图,裁剪宽度
sourceWidth = img.height;
sourceX = (img.width - sourceWidth) / 2;
} else if (aspectRatio < 1) {
// 高图,裁剪高度
sourceHeight = img.width;
sourceY = (img.height - sourceHeight) / 2;
}
ctx.drawImage(img, sourceX, sourceY, sourceWidth, sourceHeight, 0, 0, size, size);
} else {
// 适应模式
if (aspectRatio > 1) {
drawHeight = size / aspectRatio;
offsetY = (size - drawHeight) / 2;
} else {
drawWidth = size * aspectRatio;
offsetX = (size - drawWidth) / 2;
}
ctx.drawImage(img, offsetX, offsetY, drawWidth, drawHeight);
}
} else {
// 拉伸模式
ctx.drawImage(img, 0, 0, size, size);
}
// 如果是圆形或圆角方形,应用裁剪蒙版
if (selectedShape === 'circle' || selectedShape === 'rounded') {
ctx.globalCompositeOperation = 'destination-in';
if (selectedShape === 'circle') {
ctx.beginPath();
ctx.arc(size/2, size/2, size/2, 0, Math.PI * 2);
ctx.fill();
} else {
const radius = size * 0.1;
ctx.beginPath();
ctx.moveTo(radius, 0);
ctx.lineTo(size - radius, 0);
ctx.arcTo(size, 0, size, radius, radius);
ctx.lineTo(size, size - radius);
ctx.arcTo(size, size, size - radius, size, radius);
ctx.lineTo(radius, size);
ctx.arcTo(0, size, 0, size - radius, radius);
ctx.lineTo(0, radius);
ctx.arcTo(0, 0, radius, 0, radius);
ctx.closePath();
ctx.fill();
}
ctx.globalCompositeOperation = 'source-over';
}
// 如果是预览画布,更新尺寸预览
if (canvas === previewCanvas) {
updateSizePreviews();
}
};
img.src = imageObjectURL;
}
// 下载PNG
downloadPngBtn.addEventListener('click', async function() {
try {
const fileName = getCustomFileName('png');
initProgressBar('PNG', fileName);
const canvas = createCanvas(selectedSize);
if (currentTab === 'text-tab') {
const drawParams = getDrawParams();
drawIcon(canvas, selectedSize, drawParams);
} else {
drawImageIcon(canvas, selectedSize);
}
// 等待图片加载完成(如果是图片模式)
setTimeout(() => {
const link = document.createElement('a');
link.download = fileName;
link.href = canvas.toDataURL('image/png');
link.click();
closeProgressBar();
}, currentTab === 'image-tab' ? 1500 : 1200);
} catch (error) {
console.error('PNG下载错误:', error);
alert('PNG下载失败,请重试');
progressModal.classList.remove('active');
}
});
// 下载ICO
downloadIcoBtn.addEventListener('click', async function() {
try {
const fileName = getCustomFileName('ico');
initProgressBar('ICO', fileName);
const canvas = createCanvas(selectedSize);
if (currentTab === 'text-tab') {
const drawParams = getDrawParams();
drawIcon(canvas, selectedSize, drawParams);
} else {
drawImageIcon(canvas, selectedSize);
}
// 等待图片加载完成(如果是图片模式)
setTimeout(() => {
const pngData = canvas.toDataURL('image/png').split(',')[1];
const pngBuffer = Uint8Array.from(atob(pngData), c => c.charCodeAt(0));
const icoHeader = new Uint8Array([0,0,1,0,1,0]);
const icoDir = new Uint8Array(16);
icoDir[0] = icoDir[1] = selectedSize > 255 ? 0 : selectedSize;
icoDir[2] = 0; icoDir[3] = 0; icoDir[4] = 1; icoDir[5] = 0;
icoDir[6] = 32; icoDir[7] = 0;
const size = pngBuffer.length;
icoDir[8] = size & 0xFF; icoDir[9] = (size >> 8) & 0xFF;
icoDir[10] = (size >> 16) & 0xFF; icoDir[11] = (size >> 24) & 0xFF;
const offset = icoHeader.length + icoDir.length;
icoDir[12] = offset & 0xFF; icoDir[13] = (offset >> 8) & 0xFF;
icoDir[14] = (offset >> 16) & 0xFF; icoDir[15] = (offset >> 24) & 0xFF;
const icoData = new Uint8Array(icoHeader.length + icoDir.length + pngBuffer.length);
icoData.set(icoHeader);
icoData.set(icoDir, icoHeader.length);
icoData.set(pngBuffer, icoHeader.length + icoDir.length);
const blob = new Blob([icoData], { type: 'image/x-icon' });
const link = document.createElement('a');
link.href = URL.createObjectURL(blob);
link.download = fileName;
document.body.appendChild(link);
link.click();
setTimeout(() => {
document.body.removeChild(link);
URL.revokeObjectURL(link.href);
closeProgressBar();
}, 100);
}, currentTab === 'image-tab' ? 1500 : 1200);
} catch (error) {
console.error('ICO下载错误:', error);
alert('ICO下载失败,请重试');
progressModal.classList.remove('active');
}
});
// 下载SVG
downloadSvgBtn.addEventListener('click', async function() {
try {
const fileName = getCustomFileName('svg');
initProgressBar('SVG', fileName);
if (currentTab === 'text-tab') {
const drawParams = getDrawParams();
const canvas = createCanvas(selectedSize);
const drawResult = drawIcon(canvas, selectedSize, drawParams);
const fontInfo = await getSvgFontInfo(drawParams.font);
const svgString = generateSvgString(selectedSize, {
...drawParams,
...drawResult,
fontInfo: fontInfo,
svgVerticalAdjust: parseInt(svgVerticalAdjust.value),
svgHorizontalAdjust: parseInt(svgHorizontalAdjust.value)
});
const blob = new Blob([svgString], { type: 'image/svg+xml;charset=utf-8' });
const url = URL.createObjectURL(blob);
const link = document.createElement('a');
link.href = url;
link.download = fileName;
setTimeout(() => {
link.click();
URL.revokeObjectURL(url);
closeProgressBar();
}, 1200);
} else {
// 图片转SVG
if (!uploadedImage) {
throw new Error('请先上传图片');
}
// 创建图片的dataURL
const tempCanvas = createCanvas(selectedSize);
drawImageIcon(tempCanvas, selectedSize);
setTimeout(() => {
const imageDataUrl = tempCanvas.toDataURL('image/png');
// 生成包含图片的SVG
let svgContent = `<svg width="${selectedSize}" height="${selectedSize}" xmlns="http://www.w3.org/2000/svg">`;
// 添加背景(如果需要)
if (!imageTransparentBg.checked) {
if (selectedShape === 'circle') {
svgContent += `<circle cx="${selectedSize/2}" cy="${selectedSize/2}" r="${selectedSize/2}" fill="white" />`;
} else if (selectedShape === 'rounded') {
const radius = selectedSize * 0.1;
svgContent += `<rect x="0" y="0" width="${selectedSize}" height="${selectedSize}" rx="${radius}" ry="${radius}" fill="white" />`;
} else {
svgContent += `<rect width="${selectedSize}" height="${selectedSize}" fill="white" />`;
}
}
// 添加图片
svgContent += `<image href="${imageDataUrl}" width="${selectedSize}" height="${selectedSize}" />`;
// 添加裁剪蒙版(如果需要)
if (selectedShape === 'circle' || selectedShape === 'rounded') {
svgContent += `<defs><clipPath id="clipShape">`;
if (selectedShape === 'circle') {
svgContent += `<circle cx="${selectedSize/2}" cy="${selectedSize/2}" r="${selectedSize/2}" />`;
} else {
const radius = selectedSize * 0.1;
svgContent += `<rect x="0" y="0" width="${selectedSize}" height="${selectedSize}" rx="${radius}" ry="${radius}" />`;
}
svgContent += `</clipPath></defs>`;
svgContent += `<rect width="${selectedSize}" height="${selectedSize}" fill="transparent" clip-path="url(#clipShape)" />`;
}
svgContent += `</svg>`;
const blob = new Blob([svgContent], { type: 'image/svg+xml;charset=utf-8' });
const url = URL.createObjectURL(blob);
const link = document.createElement('a');
link.href = url;
link.download = fileName;
link.click();
URL.revokeObjectURL(url);
closeProgressBar();
}, 1500);
}
} catch (error) {
console.error('SVG生成错误:', error);
alert('SVG下载失败,请重试(错误:' + error.message + ')');
progressModal.classList.remove('active');
}
});
// 获取SVG字体信息
async function getSvgFontInfo(selectedFontFamily) {
if (uploadedFonts.has(selectedFontFamily)) {
const fontData = uploadedFonts.get(selectedFontFamily);
if (!fontData.dataUrl) {
const response = await fetch(fontData.url);
const blob = await response.blob();
const reader = new FileReader();
const dataUrl = await new Promise((resolve) => {
reader.onloadend = () => resolve(reader.result);
reader.readAsDataURL(blob);
});
fontData.dataUrl = dataUrl;
uploadedFonts.set(selectedFontFamily, fontData);
}
return {
type: 'uploaded',
family: selectedFontFamily,
dataUrl: fontData.dataUrl,
fileName: fontData.fileName
};
} else {
const fontOption = Array.from(fontSelect.options).find(
opt => opt.value === selectedFontFamily
);
const aliases = fontOption ? JSON.parse(fontOption.dataset.aliases) : [selectedFontFamily];
const fallbackMap = {
'SimSun': ['serif', 'STSong', 'NSimSun'],
'Microsoft YaHei': ['sans-serif', '微软雅黑', 'SimHei'],
'KaiTi': ['STKaiti', 'serif']
};
const fallbacks = fallbackMap[selectedFontFamily] || [];
const allFonts = [...new Set([selectedFontFamily, ...aliases, ...fallbacks])];
return {
type: 'built-in',
family: selectedFontFamily,
fallbacks: allFonts
};
}
}
// 创建Canvas
function createCanvas(size) {
const canvas = document.createElement('canvas');
canvas.width = size;
canvas.height = size;
return canvas;
}
// 获取绘制参数
function getDrawParams() {
return {
text: textInput.value,
font: fontSelect.value,
textColor: colorInput.value,
bgColor: bgColorInput.value,
transparent: transparentBg.checked,
shape: selectedShape,
size: selectedSize,
position: selectedPosition,
autoWrap: autoWrap.checked,
textCenter: textCenter.checked,
autoStretch: autoStretch.checked,
fontSize: parseInt(fontSizeSlider.value),
horizontalStretch: parseInt(horizontalStretch.value),
verticalStretch: parseInt(verticalStretch.value),
horizontalOffset: parseInt(horizontalOffset.value),
verticalOffset: parseInt(verticalOffset.value)
};
}
// 根据九宫格位置计算对齐方式
function getPositionAlignment(position) {
const alignments = {
'top-left': { textAlign: 'left', textBaseline: 'top', x: 0.1, y: 0.1 },
'top-center': { textAlign: 'center', textBaseline: 'top', x: 0.5, y: 0.1 },
'top-right': { textAlign: 'right', textBaseline: 'top', x: 0.9, y: 0.1 },
'center-left': { textAlign: 'left', textBaseline: 'middle', x: 0.1, y: 0.5 },
'center-center': { textAlign: 'center', textBaseline: 'middle', x: 0.5, y: 0.5 },
'center-right': { textAlign: 'right', textBaseline: 'middle', x: 0.9, y: 0.5 },
'bottom-left': { textAlign: 'left', textBaseline: 'bottom', x: 0.1, y: 0.9 },
'bottom-center': { textAlign: 'center', textBaseline: 'bottom', x: 0.5, y: 0.9 },
'bottom-right': { textAlign: 'right', textBaseline: 'bottom', x: 0.9, y: 0.9 }
};
return alignments[position] || alignments['center-center'];
}
// 绘制图标
function drawIcon(canvas, size, params) {
const ctx = canvas.getContext('2d');
ctx.clearRect(0, 0, size, size);
// 绘制背景
if (!params.transparent) {
ctx.fillStyle = params.bgColor;
if (params.shape === 'circle') {
ctx.beginPath();
ctx.arc(size/2, size/2, size/2, 0, Math.PI * 2);
ctx.fill();
} else if (params.shape === 'rounded') {
const radius = size * 0.1;
ctx.beginPath();
ctx.moveTo(radius, 0);
ctx.lineTo(size - radius, 0);
ctx.arcTo(size, 0, size, radius, radius);
ctx.lineTo(size, size - radius);
ctx.arcTo(size, size, size - radius, size, radius);
ctx.lineTo(radius, size);
ctx.arcTo(0, size, 0, size - radius, radius);
ctx.lineTo(0, radius);
ctx.arcTo(0, 0, radius, 0, radius);
ctx.closePath();
ctx.fill();
} else {
ctx.fillRect(0, 0, size, size);
}
}
// 处理文字换行
let lines = [];
if (params.autoWrap) {
const words = params.text.replace(/\n/g, ' ').split(' ');
let currentLine = '';
words.forEach(word => {
if (currentLine.length + word.length < 10) {
currentLine += (currentLine ? ' ' : '') + word;
} else {
if (currentLine) lines.push(currentLine);
currentLine = word;
}
});
if (currentLine) lines.push(currentLine);
} else {
lines = params.text.split('\n');
}
// 计算字体大小
const fontSize = params.autoStretch ? size * 0.3 : size * params.fontSize / 100;
// 获取位置对齐信息
const positionAlign = getPositionAlignment(params.position);
// 设置字体和颜色
ctx.fillStyle = params.textColor;
ctx.font = `${fontSize}px ${params.font}`;
// 计算文本位置
const textX = size * positionAlign.x + params.horizontalOffset;
const textY = size * positionAlign.y + params.verticalOffset;
// 计算行高和总高度
const lineHeight = fontSize * 1.2;
const totalTextHeight = (lines.length - 1) * lineHeight;
// 应用拉伸变换
ctx.save();
// 计算变换中心点
const transformX = textX;
const transformY = textY - (lines.length > 1 ? totalTextHeight / 2 : 0);
// 应用拉伸
ctx.translate(transformX, transformY);
ctx.scale(params.horizontalStretch / 100, params.verticalStretch / 100);
ctx.translate(-transformX, -transformY);
// 设置文本对齐
ctx.textAlign = positionAlign.textAlign;
ctx.textBaseline = positionAlign.textBaseline;
// 绘制多行文字
lines.forEach((line, index) => {
const lineY = textY + (index - (lines.length - 1) / 2) * lineHeight;
ctx.fillText(line, textX, lineY);
});
ctx.restore();
return {
lines: lines,
lineHeight: lineHeight,
fontSize: fontSize,
textX: textX,
textY: textY,
positionAlign: positionAlign,
transformX: transformX,
transformY: transformY
};
}
// 生成SVG字符串
function generateSvgString(size, params) {
const { text, textColor, bgColor, transparent, shape, position,
lines, lineHeight, fontSize, textX, textY, positionAlign,
transformX, transformY, fontInfo,
svgVerticalAdjust, svgHorizontalAdjust,
horizontalStretch, verticalStretch,
horizontalOffset, verticalOffset } = params;
// 处理背景
let bgElement = '';
if (!transparent) {
let bgShape = '';
if (shape === 'circle') {
bgShape = `<circle cx="${size/2}" cy="${size/2}" r="${size/2}" fill="${bgColor}" />`;
} else if (shape === 'rounded') {
const radius = size * 0.1;
bgShape = `<rect x="0" y="0" width="${size}" height="${size}" rx="${radius}" ry="${radius}" fill="${bgColor}" />`;
} else {
bgShape = `<rect x="0" y="0" width="${size}" height="${size}" fill="${bgColor}" />`;
}
bgElement = bgShape;
}
// 处理字体嵌入
let fontStyle = '';
if (fontInfo.type === 'uploaded') {
fontStyle = `<style>
@font-face {
font-family: '${fontInfo.family}';
src: url('${fontInfo.dataUrl}') format('truetype');
}
.text { font-family: '${fontInfo.family}'; }
</style>`;
} else {
const fontFamilies = fontInfo.fallbacks.join(', ');
fontStyle = `<style>
.text { font-family: ${fontFamilies}; }
text { dominant-baseline: central; }
</style>`;
}
// 计算文本位置和对齐
const textAnchorMap = {
'left': 'start',
'center': 'middle',
'right': 'end'
};
// SVG的baseline处理与Canvas不同,需要调整
const svgTextY = textY + svgVerticalAdjust;
const svgTextX = textX + svgHorizontalAdjust;
// 计算变换参数 - 修复SVG变换中心问题
const scaleX = horizontalStretch / 100;
const scaleY = verticalStretch / 100;
// 调整变换中心,确保缩放后位置正确
const translateX = transformX - (transformX * scaleX) + (svgTextX * (scaleX - 1));
const translateY = transformY - (transformY * scaleY) + ((svgTextY) * (scaleY - 1));
// 构建变换字符串
const transform = `translate(${translateX}, ${translateY}) scale(${scaleX}, ${scaleY})`;
// 生成文本元素
let textElements = '';
lines.forEach((line, index) => {
const lineY = svgTextY + (index - (lines.length - 1) / 2) * lineHeight;
textElements += `<text
x="${svgTextX}"
y="${lineY}"
text-anchor="${textAnchorMap[positionAlign.textAlign]}"
dominant-baseline="middle"
fill="${textColor}"
class="text"
font-size="${fontSize}">
${escapeXml(line)}
</text>`;
});
// 组合SVG
return `<svg width="${size}" height="${size}" xmlns="http://www.w3.org/2000/svg">
${fontStyle}
${bgElement}
<g transform="${transform}">
${textElements}
</g>
</svg>`;
}
// 转义XML特殊字符
function escapeXml(unsafe) {
return unsafe.replace(/[&<>"']/g, c => {
switch (c) {
case '&': return '&';
case '<': return '<';
case '>': return '>';
case '"': return '"';
case "'": return ''';
default: return c;
}
});
}
// 更新预览
function updatePreview() {
if (currentTab === 'text-tab') {
const params = getDrawParams();
drawIcon(previewCanvas, 256, params);
} else {
drawImageIcon(previewCanvas, 256);
}
updateSizePreviews();
}
// 更新尺寸预览
function updateSizePreviews() {
sizePreview.innerHTML = '';
[16, 32, 48, 64, 128].forEach(size => {
const canvas = createCanvas(size);
canvas.className = 'size-preview-canvas';
canvas.width = size;
canvas.height = size;
canvas.title = `${size}×${size}`;
const item = document.createElement('div');
item.className = 'size-preview-item';
item.innerHTML = `<div>${size}×${size}</div>`;
item.appendChild(canvas);
sizePreview.appendChild(item);
if (currentTab === 'text-tab') {
drawIcon(canvas, size, getDrawParams());
} else {
drawImageIcon(canvas, size);
}
});
}
// 切换标签页
function switchTab(tabId) {
// 更新标签状态
tabButtons.forEach(btn => {
btn.classList.toggle('active', btn.dataset.tab === tabId);
});
tabContents.forEach(content => {
content.classList.toggle('active', content.id === tabId);
});
currentTab = tabId;
// 更新预览
updatePreview();
}
// 处理图片上传
function handleImageUpload(file) {
if (!file.type.startsWith('image/')) {
alert('请上传图片文件!');
return;
}
// 撤销之前的ObjectURL
if (imageObjectURL) {
URL.revokeObjectURL(imageObjectURL);
}
uploadedImage = file;
imageObjectURL = URL.createObjectURL(file);
// 更新预览
uploadedImagePreview.src = imageObjectURL;
uploadedImagePreview.style.display = 'block';
noImageText.style.display = 'none';
clearImageBtn.style.display = 'block';
// 显示成功消息
imageUploadSuccessMsg.style.display = 'block';
setTimeout(() => {
imageUploadSuccessMsg.style.display = 'none';
}, 3000);
// 更新图标预览
updatePreview();
}
// 清空图片
function clearImage() {
if (imageObjectURL) {
URL.revokeObjectURL(imageObjectURL);
imageObjectURL = null;
}
uploadedImage = null;
uploadedImagePreview.src = '';
uploadedImagePreview.style.display = 'none';
noImageText.style.display = 'block';
clearImageBtn.style.display = 'none';
imageFileInput.value = '';
// 更新预览
updatePreview();
}
// ========== 事件监听器 ==========
// 标签页切换
tabButtons.forEach(btn => {
btn.addEventListener('click', () => {
switchTab(btn.dataset.tab);
});
});
// 图片上传
imageFileInput.addEventListener('change', (e) => {
const file = e.target.files[0];
if (file) {
handleImageUpload(file);
}
});
// 清空图片按钮事件
clearImageBtn.addEventListener('click', clearImage);
// 图片处理选项变化事件
[imageKeepAspectRatio, imageAutoCrop, imageTransparentBg].forEach(option => {
option.addEventListener('change', updatePreview);
});
// 文字输入事件
textInput.addEventListener('input', function() {
const length = this.value.length;
charCount.textContent = length;
charCount.classList.toggle('max-chars', length >= 20);
manualWrapHint.classList.toggle('active', !autoWrap.checked);
updatePreview();
});
// 自动换行开关事件
autoWrap.addEventListener('change', function() {
manualWrapHint.classList.toggle('active', !this.checked);
updatePreview();
});
// 文字居中开关事件
textCenter.addEventListener('change', updatePreview);
// 颜色选择事件
colorInput.addEventListener('input', function() {
colorPreview.style.backgroundColor = this.value;
updatePreview();
});
bgColorInput.addEventListener('input', function() {
bgColorPreview.style.backgroundColor = this.value;
updatePreview();
});
// 透明背景开关事件
transparentBg.addEventListener('change', updatePreview);
// 形状选择事件
shapeOptions.forEach(option => {
option.addEventListener('click', function() {
shapeOptions.forEach(opt => opt.classList.remove('active'));
this.classList.add('active');
selectedShape = this.dataset.shape;
updatePreview();
});
});
// 尺寸选择事件
sizeOptions.forEach(option => {
option.addEventListener('click', function() {
sizeOptions.forEach(opt => opt.classList.remove('active'));
this.classList.add('active');
selectedSize = parseInt(this.dataset.size);
updatePreview();
});
});
// 位置选择事件
positionOptions.forEach(option => {
option.addEventListener('click', function() {
positionOptions.forEach(opt => opt.classList.remove('active'));
this.classList.add('active');
selectedPosition = this.dataset.position;
updatePreview();
});
});
// 字体选择变化事件
fontSelect.addEventListener('change', updatePreview);
// 字体上传事件
fontFileInput.addEventListener('change', async function(e) {
const files = e.target.files;
if (!files.length) return;
for (const file of files) {
try {
const fontName = `CustomFont_${fontCounter++}_${file.name.replace(/\.[^/.]+$/, "")}`;
const fontUrl = URL.createObjectURL(file);
// 创建FontFace对象
const fontFace = new FontFace(fontName, `url(${fontUrl})`);
await fontFace.load();
// 添加到文档
document.fonts.add(fontFace);
// 保存到上传字体映射
uploadedFonts.set(fontName, {
face: fontFace,
url: fontUrl,
dataUrl: null,
fileName: file.name
});
// 添加到字体选择框
const option = document.createElement('option');
option.value = fontName;
option.textContent = ` 📁 ${file.name} (自定义)`;
option.dataset.aliases = JSON.stringify([fontName]);
fontSelect.appendChild(option);
// 显示成功消息
uploadSuccessMsg.style.display = 'block';
setTimeout(() => {
uploadSuccessMsg.style.display = 'none';
}, 3000);
} catch (error) {
console.error('字体加载失败:', error);
alert(`字体"${file.name}"加载失败: ${error.message}`);
}
}
// 清空文件输入
this.value = '';
});
// 拉伸控制滑块事件
horizontalStretch.addEventListener('input', function() {
horizontalValue.textContent = `${this.value}%`;
if (stretchFollowFont.checked && !autoStretch.checked) {
verticalStretch.value = Math.round(this.value * baseStretch.vertical / baseStretch.horizontal);
verticalValue.textContent = `${verticalStretch.value}%`;
}
updatePreview();
});
verticalStretch.addEventListener('input', function() {
verticalValue.textContent = `${this.value}%`;
updatePreview();
});
horizontalOffset.addEventListener('input', function() {
horizontalOffsetValue.textContent = `${this.value}px`;
updatePreview();
});
verticalOffset.addEventListener('input', function() {
verticalOffsetValue.textContent = `${this.value}px`;
updatePreview();
});
svgVerticalAdjust.addEventListener('input', function() {
svgVerticalAdjustValue.textContent = `${this.value}px`;
// 仅SVG需要,这里更新预览不影响Canvas,但保持一致性
updatePreview();
});
svgHorizontalAdjust.addEventListener('input', function() {
svgHorizontalAdjustValue.textContent = `${this.value}px`;
updatePreview();
});
// 自动拉伸开关事件
autoStretch.addEventListener('change', function() {
fontSizeSlider.disabled = this.checked;
if (this.checked) {
// 重置拉伸比例到默认
horizontalStretch.value = baseStretch.horizontal;
verticalStretch.value = baseStretch.vertical;
horizontalValue.textContent = `${baseStretch.horizontal}%`;
verticalValue.textContent = `${baseStretch.vertical}%`;
}
updatePreview();
});
// 拉伸跟随字体开关事件
stretchFollowFont.addEventListener('change', function() {
if (this.checked && !autoStretch.checked) {
// 同步拉伸比例
verticalStretch.value = Math.round(horizontalStretch.value * baseStretch.vertical / baseStretch.horizontal);
verticalValue.textContent = `${verticalStretch.value}%`;
}
updatePreview();
});
// 字体大小滑块事件
fontSizeSlider.addEventListener('input', function() {
fontSizeValue.textContent = `${this.value}%`;
updatePreview();
});
// 初始化颜色预览
colorPreview.style.backgroundColor = colorInput.value;
bgColorPreview.style.backgroundColor = bgColorInput.value;
manualWrapHint.classList.toggle('active', !autoWrap.checked);
// 初始化预览
updatePreview();
});
</script>
</body>
</html>
|
免费评分
-
| 参与人数 5 | 吾爱币 +12 |
热心值 +5 |
收起
理由
|
dada02
| + 1 |
+ 1 |
鼓励转贴优秀软件安全工具和文档! |
hrh123
| + 7 |
+ 1 |
欢迎分析讨论交流,吾爱破解论坛有你更精彩! |
小酒窝
| + 2 |
+ 1 |
鼓励转贴优秀软件安全工具和文档! |
策士
| + 1 |
+ 1 |
鼓励转贴优秀软件安全工具和文档! |
Flanders
| + 1 |
+ 1 |
感谢发布原创作品,吾爱破解论坛因你更精彩! |
查看全部评分
本帖被以下淘专辑推荐:
- · 软件合辑|主题: 4801, 订阅: 2840
- · 我觉得有用的一|主题: 287, 订阅: 64
- · 收藏帖子|主题: 2027, 订阅: 62
|