689 lines
29 KiB
JavaScript
689 lines
29 KiB
JavaScript
/* 「位图转矢量」的 UI 与交互(potrace 版:单色 / 灰度)。
|
||
*
|
||
* 设计取舍:
|
||
* 1. 面板只渲染一次,参数变化走 syncControls() 回写控件值 —— 重建 innerHTML 会打断滑杆拖动;
|
||
* 2. 预览用 <img src="blob:"> 而不是 innerHTML 插 SVG —— 宿主 CSP 下更安全,也避免每次重绘解析 DOM;
|
||
* 3. potrace 是**同步**纯 JS(800px 几十毫秒),所以没有上一版那种 busy/pending 重入状态机,
|
||
* 只保留 150ms 防抖 + seq 票据(关闭时让在途回调失效);
|
||
* 4. 参数记忆走 ctx.settings(宿主命名空间 KV),下次打开回到上次的参数。
|
||
*
|
||
* 面板刻意做小:用户只做单色/灰度,高频就「方式 + 层数 + 去小点」三个,
|
||
* 阈值/反相/颜色收进高级(0 层级优先,低频 1 层级)。
|
||
*/
|
||
'use strict'
|
||
|
||
import { DEFAULTS, LEVELS_MIN, LEVELS_MAX, TOLERANCE_TONES, normalizeParams } from './engine.js'
|
||
import { loadImage, prepareSource, svgToPngBlob, svgStats } from './trace.js'
|
||
import { traceImageData } from './engine.js'
|
||
|
||
const SETTING_KEYS = ['preset', 'mode', 'levels', 'threshold', 'turdSize', 'alphaMax', 'optTolerance', 'invert', 'color', 'bg', 'bgExport', 'outScale', 'advOpen', 'splitIslands']
|
||
|
||
/** 三个预设:都围绕「自己出图」的实际场景,不放没用的组合 */
|
||
const PRESETS = {
|
||
text: { label: '文字 / 线稿', hint: '单色 · 保笔画', mode: 'mono', turdSize: 2, alphaMax: 1, levels: 3 },
|
||
menu: { label: '菜单 / 图文', hint: '灰度 3 层', mode: 'gray', levels: 3, turdSize: 4, alphaMax: 1 },
|
||
cutout: { label: '抠图轮廓', hint: '单色 · 去毛刺', mode: 'mono', turdSize: 12, alphaMax: 1.1, levels: 3 },
|
||
}
|
||
|
||
const HINTS = {
|
||
turdSize: '抹掉小于该像素面积的碎片(毛刺 / 噪点)',
|
||
alphaMax: '越小越硬朗(多折线),越大越圆',
|
||
}
|
||
|
||
function esc(s) {
|
||
return String(s).replace(/[&<>"']/g, function (c) {
|
||
return { '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' }[c]
|
||
})
|
||
}
|
||
|
||
function segHTML(group, options, current) {
|
||
return options.map(function (pair) {
|
||
const active = String(pair[0]) === String(current) ? ' active' : ''
|
||
return '<button type="button" class="' + active.trim() + '" data-seg="' + group + '" data-value="' + pair[0] + '">' + esc(pair[1]) + '</button>'
|
||
}).join('')
|
||
}
|
||
|
||
function rangeHTML(name, label, min, max, step, value, hint) {
|
||
return '<div class="vz-row">' +
|
||
'<div class="vz-row-label">' + esc(label) + (hint ? '<span>' + esc(hint) + '</span>' : '') + '</div>' +
|
||
'<div class="vz-range">' +
|
||
'<input type="range" data-param="' + name + '" min="' + min + '" max="' + max + '" step="' + step + '" value="' + value + '">' +
|
||
'<span class="vz-range-val" data-val="' + name + '">' + value + '</span>' +
|
||
'</div></div>'
|
||
}
|
||
|
||
function panelHTML(params, preset, outScale, advOpen) {
|
||
const presets = Object.keys(PRESETS).map(function (key) {
|
||
const p = PRESETS[key]
|
||
return '<button type="button" class="vz-preset' + (key === preset ? ' active' : '') + '" data-preset="' + key + '">' +
|
||
esc(p.label) + '<small>' + esc(p.hint) + '</small></button>'
|
||
}).join('')
|
||
|
||
return '' +
|
||
'<div class="vz-group"><div class="vz-group-title">预设</div><div class="vz-presets">' + presets + '</div></div>' +
|
||
|
||
'<div class="vz-group">' +
|
||
'<div class="vz-row"><div class="vz-row-label">描摹方式</div><div class="vz-seg" data-seg-group="mode">' +
|
||
segHTML('mode', [['gray', '灰度分层'], ['mono', '纯单色']], params.mode) + '</div></div>' +
|
||
'<div class="vz-row" data-only="gray"><div class="vz-row-label">层数<span>多一层,浅色块更容易分离</span></div><div class="vz-seg" data-seg-group="levels">' +
|
||
[2, 3, 4, 5].map(function (n) { return '<button type="button" data-seg="levels" data-value="' + n + '">' + n + '</button>' }).join('') +
|
||
'</div></div>' +
|
||
'</div>' +
|
||
|
||
'<div class="vz-group">' +
|
||
rangeHTML('turdSize', '去小点', 0, 40, 1, params.turdSize, HINTS.turdSize) +
|
||
'<div class="vz-row"><div class="vz-row-label">边缘<span>拐角处理</span></div><div class="vz-seg" data-seg-group="alphaTone">' +
|
||
'<button type="button" data-seg="alphaTone" data-value="hard">硬朗</button>' +
|
||
'<button type="button" data-seg="alphaTone" data-value="normal">标准</button>' +
|
||
'<button type="button" data-seg="alphaTone" data-value="round">圆润</button></div></div>' +
|
||
'<div class="vz-row"><div class="vz-row-label">精度<span>越高越贴合原图,曲线数据略多</span></div><div class="vz-seg" data-seg-group="precision">' +
|
||
'<button type="button" data-seg="precision" data-value="fine">精细</button>' +
|
||
'<button type="button" data-seg="precision" data-value="normal">标准</button>' +
|
||
'<button type="button" data-seg="precision" data-value="light">轻量</button></div></div>' +
|
||
'</div>' +
|
||
|
||
'<div class="vz-group">' +
|
||
'<div class="vz-row"><div class="vz-row-label">输出倍率<span>PNG 按矢量重绘,真清晰</span></div><div class="vz-seg" data-seg-group="outScale">' +
|
||
[1, 2, 3, 4].map(function (n) { return '<button type="button" data-seg="outScale" data-value="' + n + '">' + n + '×</button>' }).join('') +
|
||
'</div></div>' +
|
||
'<div class="vz-row vz-row-switch">' +
|
||
'<div class="vz-row-text">按孤岛拆分<span>每个连通块一个图层,粘到 Figma 可单独选中;笔画不连的汉字会分成几块</span></div>' +
|
||
'<label class="vz-switch"><input type="checkbox" data-check="splitIslands"' + (params.splitIslands ? ' checked' : '') + '><i></i></label>' +
|
||
'</div>' +
|
||
'</div>' +
|
||
|
||
'<div class="vz-group">' +
|
||
'<div class="vz-stats">' +
|
||
'<span><b data-stat="elements">–</b> 元素</span>' +
|
||
'<span><b data-stat="levels">–</b> 层</span>' +
|
||
'<span><b data-stat="bytes">–</b></span>' +
|
||
'<span><b data-stat="ms">–</b></span>' +
|
||
'</div>' +
|
||
'</div>' +
|
||
|
||
'<div class="vz-group">' +
|
||
'<button type="button" class="vz-adv-toggle" data-act="adv" aria-expanded="' + (advOpen ? 'true' : 'false') + '">高级参数<span data-adv-caret>' + (advOpen ? '▴' : '▾') + '</span></button>' +
|
||
'<div class="vz-adv" data-adv' + (advOpen ? '' : ' hidden') + '>' +
|
||
'<div class="vz-row"><div class="vz-row-label">阈值<span>自动按直方图取,手动可救极端图</span></div><div class="vz-seg" data-seg-group="thrMode">' +
|
||
'<button type="button" data-seg="thrMode" data-value="auto">自动</button>' +
|
||
'<button type="button" data-seg="thrMode" data-value="manual">手动</button></div></div>' +
|
||
'<div data-thr-row hidden>' + rangeHTML('threshold', '阈值取值', 0, 255, 1, params.threshold >= 0 ? params.threshold : 128, '') + '</div>' +
|
||
'<div class="vz-row"><div class="vz-row-label">反相<span>黑底白字时打开</span></div><div class="vz-seg" data-seg-group="invert">' +
|
||
segHTML('invert', [['0', '正片'], ['1', '负片']], params.invert ? 1 : 0) + '</div></div>' +
|
||
'<div class="vz-row"><div class="vz-row-label">填充 / 背景<span>填充仅「纯单色」生效 · 背景作预览底</span></div>' +
|
||
'<div class="vz-swatches">' +
|
||
'<input type="color" class="vz-color" data-color="color" value="' + esc(params.color) + '" title="填充色(纯单色生效)">' +
|
||
'<input type="color" class="vz-color" data-color="bg" value="' + esc(params.bg) + '" title="背景色(预览底;勾「带底」写入导出)">' +
|
||
'<label class="vz-mini" title="导出 / 复制时把背景色一起写进 SVG(默认不带,粘到 Figma 是透明底)">' +
|
||
'<input type="checkbox" data-check="bgExport"' + (params.bgExport ? ' checked' : '') + '><span>带底</span></label>' +
|
||
'</div></div>' +
|
||
'</div>' +
|
||
'</div>'
|
||
}
|
||
|
||
function viewHTML(name) {
|
||
return '' +
|
||
'<div class="vz-root">' +
|
||
'<div class="vz-modal" role="dialog" aria-modal="true" aria-label="位图转矢量">' +
|
||
'<header class="vz-header">' +
|
||
'<span class="vz-title">位图转矢量<em data-meta>' + esc(name) + '</em></span>' +
|
||
'<div class="vz-spacer"></div>' +
|
||
'<button type="button" class="vz-btn" data-act="cancel">取消</button>' +
|
||
'<button type="button" class="vz-btn" data-act="copy">复制 SVG</button>' +
|
||
'<button type="button" class="vz-btn" data-act="svg">下载 SVG</button>' +
|
||
'<button type="button" class="vz-btn vz-btn-primary" data-act="save">保存为节点</button>' +
|
||
'</header>' +
|
||
'<div class="vz-body">' +
|
||
'<div class="vz-preview">' +
|
||
'<img class="vz-stage" data-stage="vector" alt="矢量预览">' +
|
||
'<img class="vz-stage" data-stage="original" alt="原图" hidden>' +
|
||
'<div class="vz-badge" data-badge>矢量预览</div>' +
|
||
'<div class="vz-status" data-status hidden><i class="vz-dot"></i><span data-status-text></span></div>' +
|
||
'<div class="vz-hint">空格 对比原图 · 「复制 SVG」可直接粘到 Figma</div>' +
|
||
'</div>' +
|
||
'<aside class="vz-panel" data-panel></aside>' +
|
||
'</div></div></div>'
|
||
}
|
||
|
||
/** 边缘预设 → alphaMax(越圆 alphaMax 越大) */
|
||
const ALPHA_TONE = { hard: 0.4, normal: 1, round: 1.2 }
|
||
const toneOf = (alphaMax) => (alphaMax <= 0.6 ? 'hard' : alphaMax >= 1.1 ? 'round' : 'normal')
|
||
/** 容差 → 精度档(0.05 精细 / 0.15 标准 / 0.4 轻量) */
|
||
const tolToneOf = (tol) => (tol <= 0.08 ? 'fine' : tol >= 0.3 ? 'light' : 'normal')
|
||
|
||
export function createVectorizer(options) {
|
||
const settings = options.settings
|
||
const onSaveNode = options.onSaveNode
|
||
const onError = options.onError
|
||
const onClose = options.onClose
|
||
|
||
let root = null
|
||
let els = null
|
||
let source = null
|
||
let params = normalizeParams(DEFAULTS)
|
||
let preset = 'text'
|
||
let outScale = 2
|
||
let advOpen = true
|
||
let currentSvg = ''
|
||
let lastElements = 0
|
||
let lastIslands = 0
|
||
let currentBlobUrl = ''
|
||
let seq = 0
|
||
let debounceTimer = 0
|
||
let spaceDown = false
|
||
|
||
// ---------- 设置读写 ----------
|
||
|
||
function readSettings() {
|
||
const out = {}
|
||
if (!settings || typeof settings.get !== 'function') return out
|
||
for (const key of SETTING_KEYS) {
|
||
let value
|
||
try { value = settings.get(key) } catch (e) { continue }
|
||
if (value === undefined || value === null || value === '') continue
|
||
if (key === 'invert' || key === 'bgExport') value = value === true || value === 'true' || value === 1 || value === '1'
|
||
if (key === 'splitIslands') value = !(value === false || value === 'false' || value === 0 || value === '0')
|
||
if (key === 'advOpen') value = !(value === false || value === 'false' || value === 0 || value === '0')
|
||
out[key] = value
|
||
}
|
||
return out
|
||
}
|
||
|
||
function writeSettings() {
|
||
if (!settings || typeof settings.set !== 'function') return
|
||
try {
|
||
settings.set('preset', preset)
|
||
settings.set('mode', params.mode)
|
||
settings.set('levels', params.levels)
|
||
settings.set('threshold', params.threshold)
|
||
settings.set('turdSize', params.turdSize)
|
||
settings.set('alphaMax', params.alphaMax)
|
||
settings.set('optTolerance', params.optTolerance)
|
||
settings.set('invert', params.invert)
|
||
settings.set('color', params.color)
|
||
settings.set('bg', params.bg)
|
||
settings.set('bgExport', params.bgExport)
|
||
settings.set('outScale', outScale)
|
||
settings.set('advOpen', advOpen)
|
||
settings.set('splitIslands', params.splitIslands)
|
||
} catch (e) { /* 记忆失败不影响主流程 */ }
|
||
}
|
||
|
||
// ---------- 状态 ----------
|
||
|
||
function setStatus(kind, text) {
|
||
if (!els) return
|
||
const box = els.status
|
||
if (!kind) { box.hidden = true; box.className = 'vz-status'; return }
|
||
box.hidden = false
|
||
box.className = 'vz-status is-' + kind
|
||
els.statusText.textContent = text || ''
|
||
}
|
||
|
||
function setStats(stats, ms, levels) {
|
||
if (!els) return
|
||
const put = function (key, text) {
|
||
const node = els.panel.querySelector('[data-stat="' + key + '"]')
|
||
if (node) node.textContent = text
|
||
}
|
||
if (!stats) { put('elements', '–'); put('levels', '–'); put('bytes', '–'); put('ms', '–'); return }
|
||
const elements = stats.elements === undefined ? stats.paths : stats.elements
|
||
// 关闭拆分时元素数和真实孤岛数不等 —— 明说「合并」,否则用户会以为描摹少画了东西
|
||
put('elements', stats.islands && stats.islands !== elements
|
||
? elements + '(' + stats.islands + ' 孤岛合并)'
|
||
: String(elements))
|
||
put('levels', String(levels || 1))
|
||
put('bytes', stats.bytes >= 1024 * 1024
|
||
? (stats.bytes / 1024 / 1024).toFixed(1) + 'MB'
|
||
: Math.round(stats.bytes / 1024) + 'KB')
|
||
put('ms', ms === undefined || ms === null ? '–' : ms + 'ms')
|
||
}
|
||
|
||
/** 把 params 回写到控件(不重建 DOM,避免拖动滑杆时被打断) */
|
||
function syncControls() {
|
||
if (!els) return
|
||
const panel = els.panel
|
||
panel.querySelectorAll('[data-preset]').forEach(function (btn) {
|
||
btn.classList.toggle('active', btn.dataset.preset === preset)
|
||
})
|
||
panel.querySelectorAll('[data-param]').forEach(function (input) {
|
||
const key = input.dataset.param
|
||
input.value = key === 'threshold' && params.threshold < 0 ? 128 : params[key]
|
||
const out = panel.querySelector('[data-val="' + key + '"]')
|
||
if (out) out.textContent = input.value
|
||
})
|
||
// 层数只在灰度下有含义;颜色只在单色下有含义 —— 直接隐藏而不是假装可调
|
||
panel.querySelectorAll('[data-only="gray"]').forEach(function (row) {
|
||
row.hidden = params.mode !== 'gray'
|
||
})
|
||
panel.querySelectorAll('[data-seg-group="levels"] button').forEach(function (btn) {
|
||
btn.classList.toggle('active', Number(btn.dataset.value) === params.levels)
|
||
})
|
||
panel.querySelectorAll('[data-seg-group="mode"] button').forEach(function (btn) {
|
||
btn.classList.toggle('active', btn.dataset.value === params.mode)
|
||
})
|
||
panel.querySelectorAll('[data-seg-group="alphaTone"] button').forEach(function (btn) {
|
||
btn.classList.toggle('active', btn.dataset.value === toneOf(params.alphaMax))
|
||
})
|
||
panel.querySelectorAll('[data-seg-group="precision"] button').forEach(function (btn) {
|
||
btn.classList.toggle('active', btn.dataset.value === tolToneOf(params.optTolerance))
|
||
})
|
||
panel.querySelectorAll('[data-seg-group="invert"] button').forEach(function (btn) {
|
||
btn.classList.toggle('active', (btn.dataset.value === '1') === params.invert)
|
||
})
|
||
panel.querySelectorAll('[data-seg-group="thrMode"] button').forEach(function (btn) {
|
||
btn.classList.toggle('active', (btn.dataset.value === 'manual') === (params.threshold >= 0))
|
||
})
|
||
panel.querySelectorAll('[data-seg-group="outScale"] button').forEach(function (btn) {
|
||
btn.classList.toggle('active', Number(btn.dataset.value) === outScale)
|
||
})
|
||
panel.querySelectorAll('[data-check]').forEach(function (input) {
|
||
input.checked = Boolean(params[input.dataset.check])
|
||
})
|
||
const thrRow = panel.querySelector('[data-thr-row]')
|
||
if (thrRow) thrRow.hidden = params.threshold < 0
|
||
// 填充色只在单色下有含义(灰度靠 layer 自身亮度),背景色两种模式都能用
|
||
panel.querySelectorAll('[data-color]').forEach(function (input) {
|
||
const key = input.dataset.color
|
||
input.value = key === 'bg' ? params.bg : params.color
|
||
const locked = key === 'color' && params.mode !== 'mono'
|
||
input.disabled = locked
|
||
input.style.opacity = locked ? '0.45' : ''
|
||
})
|
||
applyPreviewBg()
|
||
}
|
||
|
||
/** 预览底色:只改 CSS,不重描摹(背景不参与轮廓计算) */
|
||
function applyPreviewBg() {
|
||
if (!els || !els.preview) return
|
||
els.preview.style.backgroundColor = params.bg
|
||
}
|
||
|
||
function releasePreview() {
|
||
if (currentBlobUrl) {
|
||
URL.revokeObjectURL(currentBlobUrl)
|
||
currentBlobUrl = ''
|
||
}
|
||
}
|
||
|
||
function showVector(svg) {
|
||
if (!els) return
|
||
releasePreview()
|
||
const blob = new Blob([svg], { type: 'image/svg+xml;charset=utf-8' })
|
||
currentBlobUrl = URL.createObjectURL(blob)
|
||
els.vector.src = currentBlobUrl
|
||
els.vector.hidden = false
|
||
updateBadge()
|
||
}
|
||
|
||
function updateBadge() {
|
||
if (!els) return
|
||
els.vector.hidden = spaceDown
|
||
els.original.hidden = !spaceDown
|
||
els.badge.textContent = spaceDown ? '原图' : '矢量预览'
|
||
}
|
||
|
||
// ---------- 描摹 ----------
|
||
|
||
function retrace() {
|
||
if (!source) return
|
||
const ticket = ++seq
|
||
try {
|
||
const prepared = prepareSource(source.img)
|
||
const ctx = prepared.canvas.getContext('2d', { willReadFrequently: true })
|
||
const data = ctx.getImageData(0, 0, prepared.w, prepared.h)
|
||
const out = traceImageData(data, params)
|
||
if (ticket !== seq || !els) return
|
||
currentSvg = out.svg
|
||
showVector(currentSvg)
|
||
const stats = svgStats(currentSvg)
|
||
stats.elements = out.elements
|
||
stats.islands = out.islands
|
||
lastElements = out.elements
|
||
lastIslands = out.islands
|
||
setStats(stats, out.ms, out.levels)
|
||
setStatus(null)
|
||
if (prepared.clamped) {
|
||
setStatus('busy', '大图已降到 ' + prepared.w + '×' + prepared.h + ' 再描摹')
|
||
window.setTimeout(function () { if (ticket === seq) setStatus(null) }, 2600)
|
||
} else if (params.mode === 'gray' && params.splitIslands && out.elements > 40) {
|
||
// 灰度是「每层各描一遍」,层与层之间本来就有重叠的大轮廓,
|
||
// 拆开后同位置会出现多个重复图层(在 Figma 里选一个会选中好几个)。
|
||
// 这不是拆分 bug,是分层描摹的性质 —— 明说,别让用户以为是重复元素。
|
||
setStatus('busy', '灰度按层各拆一遍(' + out.elements + ' 个元素,层间会重叠);要干净分离改用「纯单色」')
|
||
window.setTimeout(function () { if (ticket === seq) setStatus(null) }, 4200)
|
||
}
|
||
els.meta.textContent = source.name + ' · ' + prepared.srcW + '×' + prepared.srcH
|
||
} catch (error) {
|
||
if (ticket !== seq) return
|
||
currentSvg = ''
|
||
setStats(null)
|
||
const msg = error && error.message ? error.message : String(error)
|
||
setStatus('error', '描摹失败:' + msg)
|
||
if (typeof onError === 'function') onError(error)
|
||
}
|
||
}
|
||
|
||
function scheduleRetrace() {
|
||
window.clearTimeout(debounceTimer)
|
||
debounceTimer = window.setTimeout(function () { writeSettings(); retrace() }, 120)
|
||
}
|
||
|
||
// ---------- 复制到剪贴板 ----------
|
||
|
||
/**
|
||
* 把 SVG 放进剪贴板,尽量让设计软件(Figma / Illustrator / Sketch)认成**矢量**而不是文本。
|
||
*
|
||
* 三种「口味」各有用途,缺一不可:
|
||
* - `image/svg+xml`:真正的矢量 MIME,Illustrator / Inkscape 直接吃;
|
||
* - `text/html` 里带 `<svg>`:Figma 走 HTML 解析分支时会认成矢量;
|
||
* - `text/plain`:兜底(也有软件只读纯文本里的 SVG 源码)。
|
||
* Chrome 对可写 MIME 有白名单,塞了不支持的类型会**整次 write 失败**,
|
||
* 所以先用 `ClipboardItem.supports()` 探测,失败再逐级降级。
|
||
*/
|
||
async function writeSvgToClipboard(svgText) {
|
||
const nav = typeof navigator === 'undefined' ? null : navigator
|
||
const Item = typeof window === 'undefined' ? null : window.ClipboardItem
|
||
const plain = new Blob([svgText], { type: 'text/plain' })
|
||
const html = new Blob([svgText], { type: 'text/html' })
|
||
let svgFlavor = false
|
||
|
||
if (nav && nav.clipboard && typeof nav.clipboard.write === 'function' && typeof Item === 'function') {
|
||
try {
|
||
svgFlavor = typeof Item.supports !== 'function' || Item.supports('image/svg+xml')
|
||
} catch (e) {
|
||
svgFlavor = false
|
||
}
|
||
const tryWrite = async function (withSvg) {
|
||
const flavors = { 'text/plain': plain, 'text/html': html }
|
||
if (withSvg) flavors['image/svg+xml'] = new Blob([svgText], { type: 'image/svg+xml' })
|
||
await nav.clipboard.write([new Item(flavors)])
|
||
}
|
||
try {
|
||
await tryWrite(svgFlavor)
|
||
return svgFlavor ? 'svg' : 'text'
|
||
} catch (error) {
|
||
// 某个口味被拒会让整次写入失败:去掉矢量口味再试一次
|
||
if (svgFlavor) {
|
||
try {
|
||
await tryWrite(false)
|
||
return 'text'
|
||
} catch (error2) { /* 落到 writeText */ }
|
||
}
|
||
}
|
||
}
|
||
|
||
if (nav && nav.clipboard && typeof nav.clipboard.writeText === 'function') {
|
||
await nav.clipboard.writeText(svgText)
|
||
return 'text'
|
||
}
|
||
return ''
|
||
}
|
||
|
||
async function copySvg(button) {
|
||
if (!currentSvg) { setStatus('error', '还没有可复制的矢量结果'); return }
|
||
const label = button.textContent
|
||
button.disabled = true
|
||
try {
|
||
const how = await writeSvgToClipboard(currentSvg)
|
||
if (!how) throw new Error('当前环境不允许写剪贴板')
|
||
button.textContent = '已复制'
|
||
// 明确告诉用户粘过去是「散的」还是「一个整体」—— 这是本版最容易被搞混的开关
|
||
const shape = params.splitIslands
|
||
? ',粘过去是 ' + lastElements + ' 个独立元素'
|
||
: ',粘过去是 1 个整体' + (lastIslands > 1 ? '(' + lastIslands + ' 个孤岛已合并)' : '')
|
||
setStatus('busy', how === 'svg'
|
||
? '已复制矢量' + shape + ',直接粘到 Figma / Illustrator 即可'
|
||
: '已复制 SVG 源码' + shape + '(粘不进去的话改用「下载 SVG」再拖入)')
|
||
const text = els ? els.statusText.textContent : ''
|
||
window.setTimeout(function () {
|
||
if (els && els.statusText.textContent === text) setStatus(null)
|
||
}, 2600)
|
||
} catch (error) {
|
||
setStatus('error', '复制失败:' + (error && error.message ? error.message : String(error)))
|
||
} finally {
|
||
window.setTimeout(function () {
|
||
if (els) { button.disabled = false; button.textContent = label }
|
||
}, 1200)
|
||
}
|
||
}
|
||
|
||
// ---------- 输出 ----------
|
||
|
||
function downloadSvg() {
|
||
if (!currentSvg) { setStatus('error', '还没有可下载的矢量结果'); return }
|
||
const blob = new Blob([currentSvg], { type: 'image/svg+xml;charset=utf-8' })
|
||
const url = URL.createObjectURL(blob)
|
||
const a = document.createElement('a')
|
||
a.href = url
|
||
a.download = source.base + '-vector.svg'
|
||
document.body.appendChild(a)
|
||
a.click()
|
||
a.remove()
|
||
window.setTimeout(function () { URL.revokeObjectURL(url) }, 4000)
|
||
}
|
||
|
||
async function saveNode(button) {
|
||
if (!currentSvg) { setStatus('error', '还没有可保存的矢量结果'); return }
|
||
button.disabled = true
|
||
const label = button.textContent
|
||
button.textContent = '生成中…'
|
||
try {
|
||
const prepared = prepareSource(source.img)
|
||
const blob = await svgToPngBlob(currentSvg, prepared.srcW, prepared.srcH, outScale)
|
||
await onSaveNode(blob, source.base + '.png')
|
||
close()
|
||
} catch (error) {
|
||
setStatus('error', error && error.message ? error.message : String(error))
|
||
button.disabled = false
|
||
button.textContent = label
|
||
}
|
||
}
|
||
|
||
// ---------- 事件 ----------
|
||
|
||
function onPanelInput(event) {
|
||
// 勾选开关(按孤岛拆分):只影响输出形态,不动预设,但要立刻重出结果 + 更新统计
|
||
const check = event.target.closest('[data-check]')
|
||
if (check && els.panel.contains(check)) {
|
||
params[check.dataset.check] = check.checked
|
||
writeSettings()
|
||
retrace()
|
||
return
|
||
}
|
||
const swatch = event.target.closest('[data-color]')
|
||
if (swatch && els.panel.contains(swatch)) {
|
||
if (!/^#[0-9a-f]{6}$/i.test(swatch.value)) return
|
||
if (swatch.dataset.color === 'bg') {
|
||
// 背景只影响预览底,不参与轮廓计算 —— 没勾「带底」时完全不用重描摹
|
||
params.bg = swatch.value
|
||
applyPreviewBg()
|
||
writeSettings()
|
||
if (params.bgExport) scheduleRetrace()
|
||
return
|
||
}
|
||
params.color = swatch.value
|
||
preset = ''
|
||
scheduleRetrace()
|
||
return
|
||
}
|
||
const input = event.target.closest('[data-param]')
|
||
if (!input || !els.panel.contains(input)) return
|
||
const key = input.dataset.param
|
||
const raw = Number(input.value)
|
||
if (key === 'threshold') {
|
||
params.threshold = Math.max(0, Math.min(255, Math.round(raw)))
|
||
} else if (key === 'turdSize') {
|
||
params.turdSize = Math.max(0, Math.min(40, Math.round(raw)))
|
||
}
|
||
const out = els.panel.querySelector('[data-val="' + key + '"]')
|
||
if (out) out.textContent = input.value
|
||
preset = ''
|
||
scheduleRetrace()
|
||
}
|
||
|
||
function onPanelClick(event) {
|
||
const adv = event.target.closest('[data-act="adv"]')
|
||
if (adv) {
|
||
const box = els.panel.querySelector('[data-adv]')
|
||
if (box) {
|
||
const open = box.hidden
|
||
box.hidden = !open
|
||
advOpen = open
|
||
adv.setAttribute('aria-expanded', String(open))
|
||
const caret = adv.querySelector('[data-adv-caret]')
|
||
if (caret) caret.textContent = open ? '▴' : '▾'
|
||
writeSettings()
|
||
}
|
||
return
|
||
}
|
||
|
||
const presetBtn = event.target.closest('[data-preset]')
|
||
if (presetBtn) {
|
||
const key = presetBtn.dataset.preset
|
||
if (!PRESETS[key]) return
|
||
preset = key
|
||
params = normalizeParams(Object.assign({}, params, PRESETS[key]))
|
||
syncControls()
|
||
writeSettings()
|
||
retrace()
|
||
return
|
||
}
|
||
|
||
const seg = event.target.closest('[data-seg]')
|
||
if (!seg) return
|
||
const name = seg.dataset.seg
|
||
const value = seg.dataset.value
|
||
if (name === 'mode') {
|
||
params.mode = value === 'mono' ? 'mono' : 'gray'
|
||
preset = ''
|
||
} else if (name === 'levels') {
|
||
params.levels = Math.max(LEVELS_MIN, Math.min(LEVELS_MAX, Number(value) || 3))
|
||
preset = ''
|
||
} else if (name === 'alphaTone') {
|
||
params.alphaMax = ALPHA_TONE[value] === undefined ? 1 : ALPHA_TONE[value]
|
||
preset = ''
|
||
} else if (name === 'precision') {
|
||
params.optTolerance = TOLERANCE_TONES[value] === undefined ? DEFAULTS.optTolerance : TOLERANCE_TONES[value]
|
||
preset = ''
|
||
} else if (name === 'invert') {
|
||
params.invert = value === '1'
|
||
preset = ''
|
||
} else if (name === 'thrMode') {
|
||
params.threshold = value === 'manual' ? 128 : -1
|
||
preset = ''
|
||
} else if (name === 'outScale') {
|
||
outScale = Math.max(1, Math.min(4, Number(value) || 1))
|
||
writeSettings()
|
||
syncControls()
|
||
return
|
||
} else {
|
||
return
|
||
}
|
||
syncControls()
|
||
scheduleRetrace()
|
||
}
|
||
|
||
function onRootClick(event) {
|
||
const act = event.target.closest('[data-act]')
|
||
if (!act) return
|
||
const name = act.dataset.act
|
||
if (name === 'cancel') { close(); return }
|
||
if (name === 'copy') { copySvg(act); return }
|
||
if (name === 'svg') { downloadSvg(); return }
|
||
if (name === 'save') { saveNode(act); return }
|
||
}
|
||
|
||
function onKeyDown(event) {
|
||
if (!root) return
|
||
if (event.key === 'Escape') {
|
||
event.preventDefault()
|
||
event.stopPropagation()
|
||
close()
|
||
return
|
||
}
|
||
if (event.code === 'Space' && !spaceDown && !event.repeat) {
|
||
const tag = (event.target && event.target.tagName) || ''
|
||
if (tag === 'INPUT' || tag === 'TEXTAREA') return
|
||
event.preventDefault()
|
||
spaceDown = true
|
||
updateBadge()
|
||
}
|
||
}
|
||
|
||
function onKeyUp(event) {
|
||
if (event.code === 'Space' && spaceDown) {
|
||
spaceDown = false
|
||
updateBadge()
|
||
}
|
||
}
|
||
|
||
function onBlur() {
|
||
if (spaceDown) { spaceDown = false; updateBadge() }
|
||
}
|
||
|
||
function close() {
|
||
if (!root) return
|
||
seq++
|
||
window.clearTimeout(debounceTimer)
|
||
document.removeEventListener('keydown', onKeyDown, true)
|
||
document.removeEventListener('keyup', onKeyUp, true)
|
||
window.removeEventListener('blur', onBlur)
|
||
releasePreview()
|
||
const node = root
|
||
root = null
|
||
els = null
|
||
node.remove()
|
||
if (typeof onClose === 'function') onClose()
|
||
}
|
||
|
||
// ---------- 打开 ----------
|
||
|
||
async function open(request) {
|
||
if (root) close()
|
||
const stored = readSettings()
|
||
preset = PRESETS[stored.preset] ? stored.preset : 'text'
|
||
params = normalizeParams(Object.assign({}, DEFAULTS, PRESETS[preset], stored))
|
||
outScale = Math.max(1, Math.min(4, Math.round(Number(stored.outScale) || 2)))
|
||
advOpen = stored.advOpen === undefined ? true : Boolean(stored.advOpen)
|
||
|
||
const img = await loadImage(request.imageDataUrl)
|
||
const name = String(request.name || 'image.png')
|
||
const base = name.replace(/\.[^.]+$/, '') || 'image'
|
||
source = { img, name, base, srcW: img.naturalWidth || img.width, srcH: img.naturalHeight || img.height }
|
||
|
||
root = document.createElement('div')
|
||
root.innerHTML = viewHTML(name)
|
||
document.body.appendChild(root)
|
||
els = {
|
||
root,
|
||
modal: root.querySelector('.vz-modal'),
|
||
preview: root.querySelector('.vz-preview'),
|
||
panel: root.querySelector('[data-panel]'),
|
||
vector: root.querySelector('[data-stage="vector"]'),
|
||
original: root.querySelector('[data-stage="original"]'),
|
||
badge: root.querySelector('[data-badge]'),
|
||
status: root.querySelector('[data-status]'),
|
||
statusText: root.querySelector('[data-status-text]'),
|
||
meta: root.querySelector('[data-meta]'),
|
||
}
|
||
els.original.src = request.imageDataUrl
|
||
els.meta.textContent = name + ' · ' + source.srcW + '×' + source.srcH
|
||
els.panel.innerHTML = panelHTML(params, preset, outScale, advOpen)
|
||
|
||
root.addEventListener('click', onRootClick)
|
||
els.panel.addEventListener('input', onPanelInput)
|
||
els.panel.addEventListener('click', onPanelClick)
|
||
document.addEventListener('keydown', onKeyDown, true)
|
||
document.addEventListener('keyup', onKeyUp, true)
|
||
window.addEventListener('blur', onBlur)
|
||
|
||
syncControls()
|
||
setStats(null)
|
||
retrace()
|
||
return { close }
|
||
}
|
||
|
||
return { open, close }
|
||
}
|