用户实测描摹效果达不到可交付线(中文笔画断裂 / 抗锯齿边缘毛刺 / 浅色块碎层), 裁定不做这个插件。线上已清理:KV 清单移除、字节 GC 删除、宿主 `wasm-unsafe-eval` 收回。 代码本身是好的(VTracer wasm 跑通、5 预设 + 全参数面板 + 空格对比预览 + SVG/PNG 双输出、 本地 harness 27 项 + 真站 e2e 13 项全绿),问题在算法定位:VTracer 适合 logo / 线稿 / 纯平色块,不适合照片与带抗锯齿的合成图。留档备查,README 顶部已标注「已下线,未发布」。
518 lines
20 KiB
JavaScript
518 lines
20 KiB
JavaScript
/* 位图转矢量的 UI 与交互。
|
||
*
|
||
* 设计取舍:
|
||
* 1. 面板只渲染一次,参数变化走 syncControls() 回写控件值 —— 重建 innerHTML 会打断滑杆拖动;
|
||
* 2. 预览用 <img src="blob:"> 而不是 innerHTML 插 SVG —— 宿主 CSP 下更安全,也避免每次重绘解析 DOM;
|
||
* 3. 描摹是同步 wasm 调用,重入保护用 busy/pending 两态,滑杆连拖时只跑最后一次;
|
||
* 4. 调参的记忆走 ctx.settings(宿主命名空间 KV),下次打开直接回到上次的参数与预设。
|
||
*/
|
||
'use strict'
|
||
|
||
import { PRESETS, PARAM_META, clampParams, loadImage, prepareSource, cornerColor, stripBackgroundLayer, withViewBox, svgToPngBlob, svgStats, denoiseLabel } from './trace.js'
|
||
import { tracePixels } from './engine.js'
|
||
|
||
const SETTING_KEYS = ['preset', 'binary', 'hierarchical', 'mode', 'colorPrecision', 'layerDifference', 'filterSpeckle', 'cornerThreshold', 'lengthThreshold', 'maxIterations', 'denoise', 'bg', 'outScale']
|
||
|
||
const MODE_LABELS = {
|
||
hierarchical: [['stacked', '堆叠'], ['cutout', '镂空']],
|
||
mode: [['spline', '样条'], ['polygon', '多边形']],
|
||
}
|
||
|
||
function esc(s) {
|
||
return String(s).replace(/[&<>"']/g, function (c) {
|
||
return { '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' }[c]
|
||
})
|
||
}
|
||
|
||
function segHTML(name, options, current) {
|
||
return options.map(function (pair) {
|
||
const active = pair[0] === current ? ' active' : ''
|
||
return '<button type="button" class="' + active.trim() + '" data-seg="' + name + '" data-value="' + pair[0] + '">' + esc(pair[1]) + '</button>'
|
||
}).join('')
|
||
}
|
||
|
||
function rangeHTML(name, value) {
|
||
const meta = PARAM_META[name]
|
||
return '<div class="vz-row">' +
|
||
'<div class="vz-row-label">' + esc(meta.label) + '<span data-hint="' + name + '"></span></div>' +
|
||
'<div class="vz-range">' +
|
||
'<input type="range" data-param="' + name + '" min="' + meta.min + '" max="' + meta.max + '" step="' + meta.step + '" value="' + value + '">' +
|
||
'<span class="vz-range-val" data-val="' + name + '">' + value + '</span>' +
|
||
'</div></div>'
|
||
}
|
||
|
||
function panelHTML(params, preset) {
|
||
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="binary">' +
|
||
'<button type="button" data-seg="binary" data-value="color">彩色</button>' +
|
||
'<button type="button" data-seg="binary" data-value="binary">黑白</button></div></div>' +
|
||
'<div class="vz-row"><div class="vz-row-label">分层方式</div><div class="vz-seg" data-seg-group="hierarchical">' + segHTML('hierarchical', MODE_LABELS.hierarchical, params.hierarchical) + '</div></div>' +
|
||
'<div class="vz-row"><div class="vz-row-label">曲线</div><div class="vz-seg" data-seg-group="mode">' + segHTML('mode', MODE_LABELS.mode, params.mode) + '</div></div>' +
|
||
'</div>' +
|
||
|
||
'<div class="vz-group">' +
|
||
rangeHTML('colorPrecision', params.colorPrecision) +
|
||
'<div class="vz-row"><div class="vz-row-label">背景<span>贴合画布边缘的同色</span></div><div class="vz-seg" data-seg-group="bg">' +
|
||
'<button type="button" data-seg="bg" data-value="auto">去除</button>' +
|
||
'<button type="button" data-seg="bg" data-value="keep">保留</button></div></div>' +
|
||
'</div>' +
|
||
|
||
'<div class="vz-group">' +
|
||
'<div class="vz-row"><div class="vz-row-label">边缘净化<span>先降采样再描摹</span></div><div class="vz-seg" data-seg-group="denoise">' +
|
||
[1, 2, 3, 4].map(function (n) { return '<button type="button" data-seg="denoise" data-value="' + n + '">' + denoiseLabel(n) + '</button>' }).join('') +
|
||
'</div></div>' +
|
||
'<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>' +
|
||
|
||
'<div class="vz-group">' +
|
||
'<div class="vz-stats">' +
|
||
'<span><b data-stat="paths">–</b> 路径</span>' +
|
||
'<span><b data-stat="colors">–</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="false">高级参数<span data-adv-caret>▾</span></button>' +
|
||
'<div class="vz-adv" data-adv hidden>' +
|
||
rangeHTML('layerDifference', params.layerDifference) +
|
||
rangeHTML('filterSpeckle', params.filterSpeckle) +
|
||
rangeHTML('cornerThreshold', params.cornerThreshold) +
|
||
rangeHTML('lengthThreshold', params.lengthThreshold) +
|
||
rangeHTML('maxIterations', params.maxIterations) +
|
||
'<div class="vz-note">矢量结果可无限放大不失真。保存为节点输出透明底 PNG(按输出倍率超采样);需要真矢量文件请用「下载 SVG」。</div>' +
|
||
'</div>' +
|
||
'</div>'
|
||
}
|
||
|
||
function viewHTML(title, 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="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">按住空格键对比原图</div>' +
|
||
'</div>' +
|
||
'<aside class="vz-panel" data-panel></aside>' +
|
||
'</div></div></div>'
|
||
}
|
||
|
||
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 = clampParams({})
|
||
let preset = 'logo'
|
||
let outScale = 2
|
||
let currentSvg = ''
|
||
let currentBlobUrl = ''
|
||
let busy = false
|
||
let pending = false
|
||
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 === 'binary') value = value === true || value === 'true' || value === 1 || value === '1'
|
||
out[key] = value
|
||
}
|
||
return out
|
||
}
|
||
|
||
function writeSettings() {
|
||
if (!settings || typeof settings.set !== 'function') return
|
||
try {
|
||
settings.set('preset', preset)
|
||
settings.set('binary', params.binary)
|
||
settings.set('hierarchical', params.hierarchical)
|
||
settings.set('mode', params.mode)
|
||
settings.set('colorPrecision', params.colorPrecision)
|
||
settings.set('layerDifference', params.layerDifference)
|
||
settings.set('filterSpeckle', params.filterSpeckle)
|
||
settings.set('cornerThreshold', params.cornerThreshold)
|
||
settings.set('lengthThreshold', params.lengthThreshold)
|
||
settings.set('maxIterations', params.maxIterations)
|
||
settings.set('denoise', params.denoise)
|
||
settings.set('bg', params.bg)
|
||
settings.set('outScale', outScale)
|
||
} 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) {
|
||
if (!els) return
|
||
const put = function (key, text) {
|
||
const node = els.panel.querySelector('[data-stat="' + key + '"]')
|
||
if (node) node.textContent = text
|
||
}
|
||
if (!stats) { put('paths', '–'); put('colors', '–'); put('bytes', '–'); put('ms', '–'); return }
|
||
put('paths', String(stats.paths))
|
||
put('colors', String(stats.colors))
|
||
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 = params[key]
|
||
const out = panel.querySelector('[data-val="' + key + '"]')
|
||
if (out) out.textContent = params[key]
|
||
// 黑白模式不使用颜色聚类,颜色精度/色层差异在引擎里不生效 —— 直接禁用而不是假装可调
|
||
const dead = params.binary && (key === 'colorPrecision' || key === 'layerDifference')
|
||
input.disabled = dead
|
||
if (out) out.parentElement.style.opacity = dead ? '0.45' : ''
|
||
})
|
||
panel.querySelectorAll('[data-seg-group="binary"] button').forEach(function (btn) {
|
||
btn.classList.toggle('active', (btn.dataset.value === 'binary') === params.binary)
|
||
})
|
||
for (const group of ['hierarchical', 'mode', 'bg', 'denoise', 'outScale']) {
|
||
const current = group === 'outScale' ? String(outScale) : String(params[group])
|
||
panel.querySelectorAll('[data-seg-group="' + group + '"] button').forEach(function (btn) {
|
||
btn.classList.toggle('active', btn.dataset.value === current)
|
||
})
|
||
}
|
||
}
|
||
|
||
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
|
||
const original = spaceDown
|
||
els.vector.hidden = original
|
||
els.original.hidden = !original
|
||
els.badge.textContent = original ? '原图' : '矢量预览'
|
||
}
|
||
|
||
// ---------- 描摹 ----------
|
||
|
||
async function retrace() {
|
||
if (!source) return
|
||
if (busy) { pending = true; return }
|
||
busy = true
|
||
const ticket = ++seq
|
||
setStatus('busy', '描摹中…')
|
||
try {
|
||
const prepared = prepareSource(source.img, params.denoise)
|
||
const g = prepared.canvas.getContext('2d')
|
||
const data = g.getImageData(0, 0, prepared.w, prepared.h)
|
||
// 背景处理放在描摹之后、SVG 层面:喂给引擎带 alpha 的图会触发它的 color keying,
|
||
// 实测会让主体变形(红圆走形、中文笔画塌成黑块),所以描摹输入永远是原图。
|
||
const bgRgb = params.bg === 'auto' ? cornerColor(data, 20) : null
|
||
const out = await tracePixels(data.data, prepared.w, prepared.h, params)
|
||
if (ticket !== seq || !els) return
|
||
const w = prepared.srcW
|
||
const h = prepared.srcH
|
||
let traced = out.svg
|
||
let bgRemoved = false
|
||
if (bgRgb) {
|
||
const stripped = stripBackgroundLayer(traced, prepared.w, prepared.h, bgRgb)
|
||
traced = stripped.svg
|
||
bgRemoved = stripped.removed
|
||
}
|
||
currentSvg = withViewBox(traced, prepared.w, prepared.h, w, h)
|
||
showVector(currentSvg)
|
||
setStats(svgStats(currentSvg), out.ms)
|
||
const notes = []
|
||
if (bgRemoved) notes.push('已去掉背景')
|
||
if (prepared.clamped) notes.push('大图已降到 ' + prepared.w + '×' + prepared.h)
|
||
if (notes.length) {
|
||
setStatus('busy', notes.join(' · '))
|
||
window.setTimeout(function () { if (ticket === seq) setStatus(null) }, 2600)
|
||
} else {
|
||
setStatus(null)
|
||
}
|
||
els.meta.textContent = source.name + ' · ' + w + '×' + h
|
||
} catch (error) {
|
||
if (ticket !== seq) return
|
||
currentSvg = ''
|
||
setStats(null)
|
||
setStatus('error', error && error.message ? error.message : String(error))
|
||
} finally {
|
||
busy = false
|
||
if (pending) { pending = false; retrace() }
|
||
}
|
||
}
|
||
|
||
function scheduleRetrace() {
|
||
window.clearTimeout(debounceTimer)
|
||
debounceTimer = window.setTimeout(function () { writeSettings(); retrace() }, 150)
|
||
}
|
||
|
||
// ---------- 输出 ----------
|
||
|
||
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, params.denoise)
|
||
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 input = event.target.closest('[data-param]')
|
||
if (!input || !els.panel.contains(input)) return
|
||
const key = input.dataset.param
|
||
const meta = PARAM_META[key]
|
||
const raw = Number(input.value)
|
||
params[key] = Math.max(meta.min, Math.min(meta.max, Number.isFinite(raw) ? raw : params[key]))
|
||
const out = els.panel.querySelector('[data-val="' + key + '"]')
|
||
if (out) out.textContent = params[key]
|
||
// 手动调参即脱离预设(预设只是参数组合的快捷方式)
|
||
if (preset) { preset = ''; syncControls() }
|
||
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
|
||
adv.setAttribute('aria-expanded', String(open))
|
||
const caret = adv.querySelector('[data-adv-caret]')
|
||
if (caret) caret.textContent = open ? '▴' : '▾'
|
||
}
|
||
return
|
||
}
|
||
|
||
const presetBtn = event.target.closest('[data-preset]')
|
||
if (presetBtn) {
|
||
const key = presetBtn.dataset.preset
|
||
if (!PRESETS[key]) return
|
||
preset = key
|
||
params = clampParams(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 === 'binary') {
|
||
params.binary = value === 'binary'
|
||
preset = ''
|
||
} else if (name === 'denoise') {
|
||
params.denoise = Number(value)
|
||
preset = ''
|
||
} else if (name === 'bg') {
|
||
params.bg = value === 'keep' ? 'keep' : 'auto'
|
||
preset = ''
|
||
} else if (name === 'outScale') {
|
||
outScale = Number(value)
|
||
syncControls()
|
||
writeSettings()
|
||
return
|
||
} else if (name === 'hierarchical' || name === 'mode') {
|
||
params[name] = value
|
||
preset = ''
|
||
} 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 === '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++ // 让在途描摹的回调全部失效(否则关闭后仍会回写已移除的 DOM)
|
||
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 : 'logo'
|
||
params = clampParams(Object.assign({}, PRESETS[preset], stored))
|
||
outScale = Math.max(1, Math.min(4, Math.round(Number(stored.outScale) || 2)))
|
||
|
||
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'),
|
||
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)
|
||
|
||
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 }
|
||
}
|