feat(image-vectorize): v0.2 换 potrace 引擎,只做单色/灰度
用户裁定「只要单色/灰度就够」后重做:VTracer(彩色分层 wasm)换成 potrace (纯 JS,Inkscape 同款内核)。文字笔画完整、turdSize 去掉毛刺、灰度层数 2–5。 - 纯 JS ⇒ 不需要宿主放宽 CSP;插件 238KB → 116KB - 自带 potrace 移植(GPL-2.0,去 jimp 依赖,改吃 ImageData),License 随目录 - 灰度阈值自己按等像素量分位算(上游 steps:5 要 28s,这里几十 ms), 并处理「主背景峰要排除」「切点必须严格递增」两个坑 - 新增 tools/trace-cli.mjs:拿真实素材直接跑参数、出对比图 - harness 重写 32 项(含「无 wasm-unsafe-eval 的 CSP 下跑通」反向锁);真站 e2e 13 项
This commit is contained in:
1 parent
6f3a4676bb
commit
c4e4b15375
29 files changed
+5949
-2321
No files matched your search
+157
-144
@@ -1,21 +1,33 @@
|
||||
/* 位图转矢量的 UI 与交互。
|
||||
/* 「位图转矢量」的 UI 与交互(potrace 版:单色 / 灰度)。
|
||||
*
|
||||
* 设计取舍:
|
||||
* 1. 面板只渲染一次,参数变化走 syncControls() 回写控件值 —— 重建 innerHTML 会打断滑杆拖动;
|
||||
* 2. 预览用 <img src="blob:"> 而不是 innerHTML 插 SVG —— 宿主 CSP 下更安全,也避免每次重绘解析 DOM;
|
||||
* 3. 描摹是同步 wasm 调用,重入保护用 busy/pending 两态,滑杆连拖时只跑最后一次;
|
||||
* 4. 调参的记忆走 ctx.settings(宿主命名空间 KV),下次打开直接回到上次的参数与预设。
|
||||
* 3. potrace 是**同步**纯 JS(800px 几十毫秒),所以没有上一版那种 busy/pending 重入状态机,
|
||||
* 只保留 150ms 防抖 + seq 票据(关闭时让在途回调失效);
|
||||
* 4. 参数记忆走 ctx.settings(宿主命名空间 KV),下次打开回到上次的参数。
|
||||
*
|
||||
* 面板刻意做小:用户只做单色/灰度,高频就「方式 + 层数 + 去小点」三个,
|
||||
* 阈值/反相/颜色收进高级(0 层级优先,低频 1 层级)。
|
||||
*/
|
||||
'use strict'
|
||||
|
||||
import { PRESETS, PARAM_META, clampParams, loadImage, prepareSource, cornerColor, stripBackgroundLayer, withViewBox, svgToPngBlob, svgStats, denoiseLabel } from './trace.js'
|
||||
import { tracePixels } from './engine.js'
|
||||
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', 'binary', 'hierarchical', 'mode', 'colorPrecision', 'layerDifference', 'filterSpeckle', 'cornerThreshold', 'lengthThreshold', 'maxIterations', 'denoise', 'bg', 'outScale']
|
||||
const SETTING_KEYS = ['preset', 'mode', 'levels', 'threshold', 'turdSize', 'alphaMax', 'invert', 'color', 'outScale']
|
||||
|
||||
const MODE_LABELS = {
|
||||
hierarchical: [['stacked', '堆叠'], ['cutout', '镂空']],
|
||||
mode: [['spline', '样条'], ['polygon', '多边形']],
|
||||
/** 三个预设:都围绕「自己出图」的实际场景,不放没用的组合 */
|
||||
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) {
|
||||
@@ -24,24 +36,23 @@ function esc(s) {
|
||||
})
|
||||
}
|
||||
|
||||
function segHTML(name, options, current) {
|
||||
function segHTML(group, 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>'
|
||||
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, value) {
|
||||
const meta = PARAM_META[name]
|
||||
function rangeHTML(name, label, min, max, step, value, hint) {
|
||||
return '<div class="vz-row">' +
|
||||
'<div class="vz-row-label">' + esc(meta.label) + '<span data-hint="' + name + '"></span></div>' +
|
||||
'<div class="vz-row-label">' + esc(label) + (hint ? '<span>' + esc(hint) + '</span>' : '') + '</div>' +
|
||||
'<div class="vz-range">' +
|
||||
'<input type="range" data-param="' + name + '" min="' + meta.min + '" max="' + meta.max + '" step="' + meta.step + '" value="' + value + '">' +
|
||||
'<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) {
|
||||
function panelHTML(params, preset, outScale) {
|
||||
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 + '">' +
|
||||
@@ -52,25 +63,23 @@ function panelHTML(params, preset) {
|
||||
'<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 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 class="vz-row"><div class="vz-row-label">输出倍率<span>PNG 超采样</span></div><div class="vz-seg" data-seg-group="outScale">' +
|
||||
'</div>' +
|
||||
|
||||
'<div class="vz-group">' +
|
||||
rangeHTML('turdSize', '去小点', 0, 40, 1, params.turdSize, HINTS.turdSize) +
|
||||
'<div class="vz-row"><div class="vz-row-label">边缘</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>' +
|
||||
|
||||
'<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>' +
|
||||
@@ -78,7 +87,7 @@ function panelHTML(params, preset) {
|
||||
'<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="levels">–</b> 层</span>' +
|
||||
'<span><b data-stat="bytes">–</b></span>' +
|
||||
'<span><b data-stat="ms">–</b></span>' +
|
||||
'</div>' +
|
||||
@@ -87,17 +96,20 @@ function panelHTML(params, preset) {
|
||||
'<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 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>' +
|
||||
'<input type="color" class="vz-color" data-color="color" value="' + esc(params.color) + '"></div>' +
|
||||
'<div class="vz-note">矢量结果可无限放大不失真。「保存为节点」输出 PNG(按输出倍率重绘),要真矢量文件用「下载 SVG」。</div>' +
|
||||
'</div>' +
|
||||
'</div>'
|
||||
}
|
||||
|
||||
function viewHTML(title, name) {
|
||||
function viewHTML(name) {
|
||||
return '' +
|
||||
'<div class="vz-root">' +
|
||||
'<div class="vz-modal" role="dialog" aria-modal="true" aria-label="位图转矢量">' +
|
||||
@@ -120,6 +132,10 @@ function viewHTML(title, name) {
|
||||
'</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')
|
||||
|
||||
export function createVectorizer(options) {
|
||||
const settings = options.settings
|
||||
const onSaveNode = options.onSaveNode
|
||||
@@ -129,13 +145,11 @@ export function createVectorizer(options) {
|
||||
let root = null
|
||||
let els = null
|
||||
let source = null
|
||||
let params = clampParams({})
|
||||
let preset = 'logo'
|
||||
let params = normalizeParams(DEFAULTS)
|
||||
let preset = 'text'
|
||||
let outScale = 2
|
||||
let currentSvg = ''
|
||||
let currentBlobUrl = ''
|
||||
let busy = false
|
||||
let pending = false
|
||||
let seq = 0
|
||||
let debounceTimer = 0
|
||||
let spaceDown = false
|
||||
@@ -149,7 +163,7 @@ export function createVectorizer(options) {
|
||||
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'
|
||||
if (key === 'invert') value = value === true || value === 'true' || value === 1 || value === '1'
|
||||
out[key] = value
|
||||
}
|
||||
return out
|
||||
@@ -159,17 +173,13 @@ export function createVectorizer(options) {
|
||||
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('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) { /* 记忆失败不影响主流程 */ }
|
||||
}
|
||||
@@ -185,15 +195,15 @@ export function createVectorizer(options) {
|
||||
els.statusText.textContent = text || ''
|
||||
}
|
||||
|
||||
function setStats(stats, ms) {
|
||||
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('colors', '–'); put('bytes', '–'); put('ms', '–'); return }
|
||||
if (!stats) { put('paths', '–'); put('levels', '–'); put('bytes', '–'); put('ms', '–'); return }
|
||||
put('paths', String(stats.paths))
|
||||
put('colors', String(stats.colors))
|
||||
put('levels', String(levels || 1))
|
||||
put('bytes', stats.bytes >= 1024 * 1024
|
||||
? (stats.bytes / 1024 / 1024).toFixed(1) + 'MB'
|
||||
: Math.round(stats.bytes / 1024) + 'KB')
|
||||
@@ -209,22 +219,39 @@ export function createVectorizer(options) {
|
||||
})
|
||||
panel.querySelectorAll('[data-param]').forEach(function (input) {
|
||||
const key = input.dataset.param
|
||||
input.value = params[key]
|
||||
input.value = key === 'threshold' && params.threshold < 0 ? 128 : 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' : ''
|
||||
if (out) out.textContent = input.value
|
||||
})
|
||||
panel.querySelectorAll('[data-seg-group="binary"] button').forEach(function (btn) {
|
||||
btn.classList.toggle('active', (btn.dataset.value === 'binary') === params.binary)
|
||||
// 层数只在灰度下有含义;颜色只在单色下有含义 —— 直接隐藏而不是假装可调
|
||||
panel.querySelectorAll('[data-only="gray"]').forEach(function (row) {
|
||||
row.hidden = params.mode !== 'gray'
|
||||
})
|
||||
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)
|
||||
})
|
||||
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'
|
||||
}
|
||||
}
|
||||
|
||||
@@ -247,65 +274,44 @@ export function createVectorizer(options) {
|
||||
|
||||
function updateBadge() {
|
||||
if (!els) return
|
||||
const original = spaceDown
|
||||
els.vector.hidden = original
|
||||
els.original.hidden = !original
|
||||
els.badge.textContent = original ? '原图' : '矢量预览'
|
||||
els.vector.hidden = spaceDown
|
||||
els.original.hidden = !spaceDown
|
||||
els.badge.textContent = spaceDown ? '原图' : '矢量预览'
|
||||
}
|
||||
|
||||
// ---------- 描摹 ----------
|
||||
|
||||
async function retrace() {
|
||||
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)
|
||||
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
|
||||
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)
|
||||
currentSvg = out.svg
|
||||
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(' · '))
|
||||
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)
|
||||
} else {
|
||||
setStatus(null)
|
||||
}
|
||||
els.meta.textContent = source.name + ' · ' + w + '×' + h
|
||||
els.meta.textContent = source.name + ' · ' + prepared.srcW + '×' + prepared.srcH
|
||||
} 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() }
|
||||
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() }, 150)
|
||||
debounceTimer = window.setTimeout(function () { writeSettings(); retrace() }, 120)
|
||||
}
|
||||
|
||||
// ---------- 输出 ----------
|
||||
@@ -329,7 +335,7 @@ export function createVectorizer(options) {
|
||||
const label = button.textContent
|
||||
button.textContent = '生成中…'
|
||||
try {
|
||||
const prepared = prepareSource(source.img, params.denoise)
|
||||
const prepared = prepareSource(source.img)
|
||||
const blob = await svgToPngBlob(currentSvg, prepared.srcW, prepared.srcH, outScale)
|
||||
await onSaveNode(blob, source.base + '.png')
|
||||
close()
|
||||
@@ -343,16 +349,26 @@ export function createVectorizer(options) {
|
||||
// ---------- 事件 ----------
|
||||
|
||||
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 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]))
|
||||
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 = params[key]
|
||||
// 手动调参即脱离预设(预设只是参数组合的快捷方式)
|
||||
if (preset) { preset = ''; syncControls() }
|
||||
if (out) out.textContent = input.value
|
||||
preset = ''
|
||||
scheduleRetrace()
|
||||
}
|
||||
|
||||
@@ -375,7 +391,7 @@ export function createVectorizer(options) {
|
||||
const key = presetBtn.dataset.preset
|
||||
if (!PRESETS[key]) return
|
||||
preset = key
|
||||
params = clampParams(PRESETS[key])
|
||||
params = normalizeParams(Object.assign({}, params, PRESETS[key]))
|
||||
syncControls()
|
||||
writeSettings()
|
||||
retrace()
|
||||
@@ -386,23 +402,26 @@ export function createVectorizer(options) {
|
||||
if (!seg) return
|
||||
const name = seg.dataset.seg
|
||||
const value = seg.dataset.value
|
||||
if (name === 'binary') {
|
||||
params.binary = value === 'binary'
|
||||
if (name === 'mode') {
|
||||
params.mode = value === 'mono' ? 'mono' : 'gray'
|
||||
preset = ''
|
||||
} else if (name === 'denoise') {
|
||||
params.denoise = Number(value)
|
||||
} else if (name === 'levels') {
|
||||
params.levels = Math.max(LEVELS_MIN, Math.min(LEVELS_MAX, Number(value) || 3))
|
||||
preset = ''
|
||||
} else if (name === 'bg') {
|
||||
params.bg = value === 'keep' ? 'keep' : 'auto'
|
||||
} 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 = Number(value)
|
||||
syncControls()
|
||||
outScale = Math.max(1, Math.min(4, Number(value) || 1))
|
||||
writeSettings()
|
||||
syncControls()
|
||||
return
|
||||
} else if (name === 'hierarchical' || name === 'mode') {
|
||||
params[name] = value
|
||||
preset = ''
|
||||
} else {
|
||||
return
|
||||
}
|
||||
@@ -428,7 +447,6 @@ export function createVectorizer(options) {
|
||||
return
|
||||
}
|
||||
if (event.code === 'Space' && !spaceDown && !event.repeat) {
|
||||
// 空格对比原图:只在焦点不在输入控件时生效
|
||||
const tag = (event.target && event.target.tagName) || ''
|
||||
if (tag === 'INPUT' || tag === 'TEXTAREA') return
|
||||
event.preventDefault()
|
||||
@@ -450,7 +468,8 @@ export function createVectorizer(options) {
|
||||
|
||||
function close() {
|
||||
if (!root) return
|
||||
seq++ // 让在途描摹的回调全部失效(否则关闭后仍会回写已移除的 DOM)
|
||||
seq++
|
||||
window.clearTimeout(debounceTimer)
|
||||
document.removeEventListener('keydown', onKeyDown, true)
|
||||
document.removeEventListener('keyup', onKeyUp, true)
|
||||
window.removeEventListener('blur', onBlur)
|
||||
@@ -467,23 +486,17 @@ export function createVectorizer(options) {
|
||||
async function open(request) {
|
||||
if (root) close()
|
||||
const stored = readSettings()
|
||||
preset = PRESETS[stored.preset] ? stored.preset : 'logo'
|
||||
params = clampParams(Object.assign({}, PRESETS[preset], stored))
|
||||
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,
|
||||
}
|
||||
source = { img, name, base, srcW: img.naturalWidth || img.width, srcH: img.naturalHeight || img.height }
|
||||
|
||||
root = document.createElement('div')
|
||||
root.innerHTML = viewHTML('位图转矢量', name)
|
||||
root.innerHTML = viewHTML(name)
|
||||
document.body.appendChild(root)
|
||||
els = {
|
||||
root,
|
||||
@@ -498,7 +511,7 @@ export function createVectorizer(options) {
|
||||
}
|
||||
els.original.src = request.imageDataUrl
|
||||
els.meta.textContent = name + ' · ' + source.srcW + '×' + source.srcH
|
||||
els.panel.innerHTML = panelHTML(params, preset)
|
||||
els.panel.innerHTML = panelHTML(params, preset, outScale)
|
||||
|
||||
root.addEventListener('click', onRootClick)
|
||||
els.panel.addEventListener('input', onPanelInput)
|
||||
|
||||
Reference in new issue
Block a user