/* 「位图转矢量」的 UI 与交互(potrace 版:单色 / 灰度)。
*
* 设计取舍:
* 1. 面板只渲染一次,参数变化走 syncControls() 回写控件值 —— 重建 innerHTML 会打断滑杆拖动;
* 2. 预览用
而不是 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, 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', 'invert', 'color', 'outScale']
/** 三个预设:都围绕「自己出图」的实际场景,不放没用的组合 */
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 ''
}).join('')
}
function rangeHTML(name, label, min, max, step, value, hint) {
return '
' +
'
' + esc(label) + (hint ? '' + esc(hint) + '' : '') + '
' +
'
' +
'' +
'' + value + '' +
'
'
}
function panelHTML(params, preset, outScale) {
const presets = Object.keys(PRESETS).map(function (key) {
const p = PRESETS[key]
return ''
}).join('')
return '' +
'' +
'' +
'
描摹方式
' +
segHTML('mode', [['gray', '灰度分层'], ['mono', '纯单色']], params.mode) + '
' +
'
层数多一层,浅色块更容易分离
' +
[2, 3, 4, 5].map(function (n) { return '' }).join('') +
'
' +
'
' +
'' +
rangeHTML('turdSize', '去小点', 0, 40, 1, params.turdSize, HINTS.turdSize) +
'
' +
'
' +
'' +
'
输出倍率PNG 按矢量重绘,真清晰
' +
[1, 2, 3, 4].map(function (n) { return '' }).join('') +
'
' +
'
' +
'' +
'
' +
'– 路径' +
'– 层' +
'–' +
'–' +
'
' +
'
' +
'' +
'
' +
'
' +
'
阈值自动按直方图取,手动可救极端图
' +
'' +
'
' +
'
' + rangeHTML('threshold', '阈值取值', 0, 255, 1, params.threshold >= 0 ? params.threshold : 128, '') + '
' +
'
反相黑底白字时打开
' +
segHTML('invert', [['0', '正片'], ['1', '负片']], params.invert ? 1 : 0) + '
' +
'
' +
'
矢量结果可无限放大不失真。「保存为节点」输出 PNG(按输出倍率重绘),要真矢量文件用「下载 SVG」。
' +
'
' +
'
'
}
function viewHTML(name) {
return '' +
'' +
'
' +
'' +
'
' +
'
' +
'
![矢量预览]()
' +
'
![原图]()
' +
'
矢量预览
' +
'
' +
'
按住空格键对比原图
' +
'
' +
'
' +
'
'
}
/** 边缘预设 → 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')
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 currentSvg = ''
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') 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('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('invert', params.invert)
settings.set('color', params.color)
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, 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('paths', '–'); put('levels', '–'); put('bytes', '–'); put('ms', '–'); return }
put('paths', String(stats.paths))
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="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)
})
const thrRow = panel.querySelector('[data-thr-row]')
if (thrRow) thrRow.hidden = params.threshold < 0
const colorInput = panel.querySelector('[data-color="color"]')
if (colorInput) {
colorInput.value = params.color
colorInput.disabled = params.mode !== 'mono'
colorInput.parentElement.style.opacity = params.mode === 'mono' ? '' : '0.45'
}
}
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)
setStats(svgStats(currentSvg), out.ms, out.levels)
setStatus(null)
if (prepared.clamped) {
setStatus('busy', '大图已降到 ' + prepared.w + '×' + prepared.h + ' 再描摹')
window.setTimeout(function () { if (ticket === seq) setStatus(null) }, 2600)
}
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)
}
// ---------- 输出 ----------
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 color = event.target.closest('[data-color]')
if (color && els.panel.contains(color)) {
if (!/^#[0-9a-f]{6}$/i.test(color.value)) return
params.color = color.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
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 = 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 === '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 === '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)))
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, outScale)
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 }
}