用户实测描摹效果达不到可交付线(中文笔画断裂 / 抗锯齿边缘毛刺 / 浅色块碎层), 裁定不做这个插件。线上已清理:KV 清单移除、字节 GC 删除、宿主 `wasm-unsafe-eval` 收回。 代码本身是好的(VTracer wasm 跑通、5 预设 + 全参数面板 + 空格对比预览 + SVG/PNG 双输出、 本地 harness 27 项 + 真站 e2e 13 项全绿),问题在算法定位:VTracer 适合 logo / 线稿 / 纯平色块,不适合照片与带抗锯齿的合成图。留档备查,README 顶部已标注「已下线,未发布」。
269 lines
11 KiB
JavaScript
269 lines
11 KiB
JavaScript
/* 位图转矢量的业务层:预设、预处理、SVG 规范化、回栅格。
|
||
*
|
||
* 预处理为什么必要(实测 2026-11-05):单纯调 lengthThreshold / cornerThreshold 抹不掉
|
||
* rembg 那种 ±3px 的毛边 —— 引擎会忠实保留每一个像素级抖动。先把图降采样到 1/2~1/4
|
||
* (双线性插值天然把毛刺平均掉)再描摹,轮廓才真正变光滑,且耗时同步下降。
|
||
* 代价是小字/细节会糊,所以做成可选强度,默认 1x 不做。
|
||
*/
|
||
'use strict'
|
||
|
||
import { COLOR_PRECISION_MIN, COLOR_PRECISION_MAX } from './engine.js'
|
||
|
||
/** 描摹侧边长上限:超过则自动降采样(4000px 原图直描会卡住主线程好几秒) */
|
||
export const MAX_TRACE_SIDE = 2000
|
||
|
||
export const PRESETS = {
|
||
logo: {
|
||
label: '标志 / 图标',
|
||
hint: '纯色块、边缘清晰',
|
||
binary: false, hierarchical: 'stacked', mode: 'spline',
|
||
colorPrecision: 2, layerDifference: 16, filterSpeckle: 4,
|
||
cornerThreshold: 90, lengthThreshold: 3.5, maxIterations: 2, denoise: 1, bg: 'auto',
|
||
},
|
||
art: {
|
||
label: '插画 / 卡通',
|
||
hint: '色块多、有渐变',
|
||
binary: false, hierarchical: 'stacked', mode: 'spline',
|
||
colorPrecision: 3, layerDifference: 24, filterSpeckle: 4,
|
||
cornerThreshold: 90, lengthThreshold: 4, maxIterations: 2, denoise: 1,
|
||
},
|
||
photo: {
|
||
label: '照片',
|
||
hint: '色层多、体积大',
|
||
binary: false, hierarchical: 'stacked', mode: 'spline',
|
||
colorPrecision: 4, layerDifference: 48, filterSpeckle: 2,
|
||
cornerThreshold: 60, lengthThreshold: 4, maxIterations: 3, denoise: 2,
|
||
},
|
||
line: {
|
||
label: '线稿 / 黑白',
|
||
hint: '二值描摹,单色',
|
||
binary: true, hierarchical: 'stacked', mode: 'spline',
|
||
colorPrecision: 2, layerDifference: 16, filterSpeckle: 8,
|
||
cornerThreshold: 90, lengthThreshold: 4, maxIterations: 2, denoise: 1,
|
||
},
|
||
edge: {
|
||
label: '边缘净化',
|
||
hint: '清理抠图毛边,轮廓变光滑',
|
||
binary: false, hierarchical: 'stacked', mode: 'spline',
|
||
colorPrecision: 2, layerDifference: 16, filterSpeckle: 16,
|
||
cornerThreshold: 90, lengthThreshold: 6, maxIterations: 1, denoise: 3,
|
||
},
|
||
}
|
||
|
||
export const PARAM_META = {
|
||
colorPrecision: { label: '颜色精度', min: COLOR_PRECISION_MIN, max: COLOR_PRECISION_MAX, step: 1, hint: '越大色块越少(引擎阈值为反语义,已夹在 1–5)' },
|
||
layerDifference: { label: '色层差异', min: 0, max: 64, step: 2, hint: '越大越容易合并相邻色层' },
|
||
filterSpeckle: { label: '噪点过滤', min: 0, max: 128, step: 1, hint: '丢弃小于该面积的碎块' },
|
||
cornerThreshold: { label: '拐角阈值', min: 0, max: 180, step: 5, hint: '越大拐角越硬' },
|
||
lengthThreshold: { label: '路径简化', min: 0.1, max: 10, step: 0.5, hint: '越大曲线越简、节点越少' },
|
||
maxIterations: { label: '曲线迭代', min: 1, max: 10, step: 1, hint: '越大越贴合原图,但过拟合会把圆拉变形' },
|
||
}
|
||
|
||
export function clampParams(raw) {
|
||
const p = Object.assign({}, PRESETS.logo, raw || {})
|
||
const num = (key, fallback) => {
|
||
const meta = PARAM_META[key]
|
||
const n = Number(p[key])
|
||
if (!Number.isFinite(n)) return fallback
|
||
return Math.max(meta.min, Math.min(meta.max, n))
|
||
}
|
||
return {
|
||
binary: Boolean(p.binary),
|
||
hierarchical: p.hierarchical === 'cutout' ? 'cutout' : 'stacked',
|
||
mode: p.mode === 'polygon' ? 'polygon' : 'spline',
|
||
colorPrecision: Math.round(num('colorPrecision', 2)),
|
||
layerDifference: Math.round(num('layerDifference', 16)),
|
||
filterSpeckle: Math.round(num('filterSpeckle', 4)),
|
||
cornerThreshold: num('cornerThreshold', 60),
|
||
lengthThreshold: num('lengthThreshold', 3.5),
|
||
maxIterations: Math.round(num('maxIterations', 2)),
|
||
denoise: Math.max(1, Math.min(4, Math.round(Number(p.denoise) || 1))),
|
||
bg: p.bg === 'keep' ? 'keep' : 'auto',
|
||
}
|
||
}
|
||
|
||
/**
|
||
* 采样画布四角颜色(用于判断「有没有统一背景」)。
|
||
* @returns {[number,number,number]|null} 四角一致时返回该颜色,否则 null
|
||
*/
|
||
export function cornerColor(imageData, tolerance) {
|
||
const w = imageData.width
|
||
const h = imageData.height
|
||
const px = imageData.data
|
||
const tol = tolerance === undefined ? 20 : tolerance
|
||
const at = function (x, y) {
|
||
const i = (y * w + x) * 4
|
||
return [px[i], px[i + 1], px[i + 2], px[i + 3]]
|
||
}
|
||
const list = [at(0, 0), at(w - 1, 0), at(0, h - 1), at(w - 1, h - 1)].filter(function (c) { return c[3] > 8 })
|
||
if (list.length < 3) return null
|
||
const base = list[0]
|
||
for (const c of list) {
|
||
if (Math.abs(c[0] - base[0]) > tol || Math.abs(c[1] - base[1]) > tol || Math.abs(c[2] - base[2]) > tol) return null
|
||
}
|
||
return [base[0], base[1], base[2]]
|
||
}
|
||
|
||
function hexToRgb(hex) {
|
||
const m = /^#([0-9a-f]{6})$/i.exec(hex)
|
||
if (!m) return null
|
||
const n = parseInt(m[1], 16)
|
||
return [(n >> 16) & 255, (n >> 8) & 255, n & 255]
|
||
}
|
||
|
||
/** 估计一条 path 的实际包围盒:d 里的坐标对 + transform 的 translate 平移 */
|
||
function pathExtent(d, tx, ty) {
|
||
const nums = String(d).match(/-?\d+(?:\.\d+)?/g)
|
||
if (!nums || nums.length < 4) return null
|
||
let minX = Infinity, maxX = -Infinity, minY = Infinity, maxY = -Infinity
|
||
for (let i = 0; i + 1 < nums.length; i += 2) {
|
||
const x = Number(nums[i]) + tx
|
||
const y = Number(nums[i + 1]) + ty
|
||
if (!Number.isFinite(x) || !Number.isFinite(y)) continue
|
||
if (x < minX) minX = x
|
||
if (x > maxX) maxX = x
|
||
if (y < minY) minY = y
|
||
if (y > maxY) maxY = y
|
||
}
|
||
if (!Number.isFinite(minX) || !Number.isFinite(minY)) return null
|
||
return { minX, maxX, minY, maxY }
|
||
}
|
||
|
||
/**
|
||
* 从描摹结果里剔掉「铺满画布的背景层」。
|
||
*
|
||
* 为什么在 SVG 层面做,而不是描摹前把背景像素改成透明(实测走过的弯路):
|
||
* 喂给引擎带 alpha 的图会触发它的 color keying,透明区被填成 key color 后
|
||
* 与图中相近的颜色混淆 —— 实测红圆直接变形、中文笔画塌成黑块。
|
||
* 保持描摹输入是原图,只在输出里删掉那一条背景 path,主体质量不受任何影响。
|
||
*
|
||
* @param {string} svg 引擎输出
|
||
* @param {number} w 描摹宽
|
||
* @param {number} h 描摹高
|
||
* @param {[number,number,number]|null} bgRgb 四角背景色(null 则只按几何判断)
|
||
* @returns {{svg: string, removed: boolean}}
|
||
*/
|
||
export function stripBackgroundLayer(svg, w, h, bgRgb) {
|
||
const text = String(svg)
|
||
const start = text.indexOf('<path')
|
||
if (start < 0) return { svg: text, removed: false }
|
||
const end = text.indexOf('/>', start)
|
||
if (end < 0) return { svg: text, removed: false }
|
||
const tag = text.slice(start, end + 2)
|
||
|
||
const fillMatch = /fill="(#[0-9A-Fa-f]{6})"/.exec(tag)
|
||
const dMatch = /d="([^"]+)"/.exec(tag)
|
||
if (!fillMatch || !dMatch) return { svg: text, removed: false }
|
||
|
||
if (bgRgb) {
|
||
const rgb = hexToRgb(fillMatch[1])
|
||
if (!rgb) return { svg: text, removed: false }
|
||
// 背景层颜色必须与四角采样接近,否则说明第一条不是背景(透明底图/贴边主体)
|
||
const diff = Math.max(Math.abs(rgb[0] - bgRgb[0]), Math.abs(rgb[1] - bgRgb[1]), Math.abs(rgb[2] - bgRgb[2]))
|
||
if (diff > 24) return { svg: text, removed: false }
|
||
}
|
||
|
||
const tr = /translate\(\s*(-?[\d.]+)\s*[, ]\s*(-?[\d.]+)\s*\)/.exec(tag)
|
||
const ext = pathExtent(dMatch[1], tr ? Number(tr[1]) : 0, tr ? Number(tr[2]) : 0)
|
||
if (!ext) return { svg: text, removed: false }
|
||
|
||
const coverW = (ext.maxX - ext.minX) / w
|
||
const coverH = (ext.maxY - ext.minY) / h
|
||
// 覆盖 ≥85% 画布才算背景;主体满幅的图(纯色块)删掉会变成空白,靠颜色比对已经挡了一层
|
||
if (coverW < 0.85 || coverH < 0.85) return { svg: text, removed: false }
|
||
|
||
return { svg: text.slice(0, start) + text.slice(end + 2), removed: true }
|
||
}
|
||
|
||
export function loadImage(src) {
|
||
return new Promise(function (resolve, reject) {
|
||
const img = new Image()
|
||
img.onload = function () { resolve(img) }
|
||
img.onerror = function () { reject(new Error('图片解码失败')) }
|
||
img.src = src
|
||
})
|
||
}
|
||
|
||
/**
|
||
* 预处理:按 denoise 倍数降采样(并把超大图夹到 MAX_TRACE_SIDE 内)。
|
||
* @returns {{ canvas: HTMLCanvasElement, w: number, h: number, scale: number, clamped: boolean }}
|
||
*/
|
||
export function prepareSource(img, denoise) {
|
||
const srcW = img.naturalWidth || img.width
|
||
const srcH = img.naturalHeight || img.height
|
||
if (!(srcW > 0) || !(srcH > 0)) throw new Error('图片尺寸无效')
|
||
|
||
let scale = 1 / Math.max(1, Math.min(4, Math.round(denoise) || 1))
|
||
const clamped = Math.max(srcW, srcH) * scale > MAX_TRACE_SIDE
|
||
if (clamped) scale = MAX_TRACE_SIDE / Math.max(srcW, srcH)
|
||
|
||
const w = Math.max(1, Math.round(srcW * scale))
|
||
const h = Math.max(1, Math.round(srcH * scale))
|
||
const canvas = document.createElement('canvas')
|
||
canvas.width = w
|
||
canvas.height = h
|
||
const g = canvas.getContext('2d')
|
||
g.imageSmoothingEnabled = true
|
||
g.imageSmoothingQuality = 'high'
|
||
g.drawImage(img, 0, 0, w, h)
|
||
return { canvas, w, h, scale: w / srcW, clamped, srcW, srcH }
|
||
}
|
||
|
||
/**
|
||
* vtracer 产出的 svg 只有 width/height 没有 viewBox(描摹尺寸即画布尺寸)。
|
||
* 降采样后必须补 viewBox 才能放大回原始尺寸而不失真,否则浏览器按降采样尺寸渲染。
|
||
*/
|
||
export function withViewBox(svg, tracedW, tracedH, outW, outH) {
|
||
return String(svg).replace(/<svg([^>]*)>/, function (_m, attrs) {
|
||
const rest = attrs.replace(/\s(?:width|height|viewBox)="[^"]*"/g, '')
|
||
return '<svg' + rest + ' width="' + Math.round(outW) + '" height="' + Math.round(outH) +
|
||
'" viewBox="0 0 ' + tracedW + ' ' + tracedH + '" preserveAspectRatio="xMidYMid meet">'
|
||
})
|
||
}
|
||
|
||
/** SVG → 位图。走 blob: URL(宿主 img-src 放行 blob:,且不污染画布)。 */
|
||
export function svgToImage(svg) {
|
||
return new Promise(function (resolve, reject) {
|
||
const blob = new Blob([svg], { type: 'image/svg+xml;charset=utf-8' })
|
||
const url = URL.createObjectURL(blob)
|
||
const img = new Image()
|
||
img.onload = function () { URL.revokeObjectURL(url); resolve(img) }
|
||
img.onerror = function () { URL.revokeObjectURL(url); reject(new Error('矢量结果渲染失败')) }
|
||
img.src = url
|
||
})
|
||
}
|
||
|
||
/** SVG → 透明底 PNG Blob(outScale 倍超采样,边缘抗锯齿更好) */
|
||
export async function svgToPngBlob(svg, baseW, baseH, outScale) {
|
||
const img = await svgToImage(svg)
|
||
const scale = Math.max(1, Math.min(4, Math.round(outScale) || 1))
|
||
const w = Math.round(baseW * scale)
|
||
const h = Math.round(baseH * scale)
|
||
const canvas = document.createElement('canvas')
|
||
canvas.width = w
|
||
canvas.height = h
|
||
const g = canvas.getContext('2d')
|
||
g.clearRect(0, 0, w, h)
|
||
g.drawImage(img, 0, 0, w, h)
|
||
return new Promise(function (resolve, reject) {
|
||
canvas.toBlob(function (blob) {
|
||
if (blob) resolve(blob)
|
||
else reject(new Error('PNG 编码失败'))
|
||
}, 'image/png')
|
||
})
|
||
}
|
||
|
||
/** 统计:路径数、文件体积、颜色数 —— 面板底部展示,让「参数调大了会怎样」可见 */
|
||
export function svgStats(svg) {
|
||
const s = String(svg)
|
||
const paths = (s.match(/<path/g) || []).length
|
||
const colors = new Set((s.match(/fill="#[0-9A-Fa-f]{6}"/g) || []).map(function (m) { return m.toLowerCase() }))
|
||
return { paths, colors: colors.size, bytes: new Blob([s]).size }
|
||
}
|
||
|
||
/** 「1x / 1/2 / 1/3 / 1/4」的展示文案 */
|
||
export function denoiseLabel(v) {
|
||
const n = Math.max(1, Math.min(4, Math.round(v) || 1))
|
||
return n === 1 ? '原尺寸' : '1/' + n
|
||
}
|