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:
qiqi committed 2026-11-05 07:57:18 +08:00
1 parent 6f3a4676bb
commit c4e4b15375
29 files changed
+5949 -2321

No files matched your search

+152 -82
View File
@@ -1,102 +1,172 @@
/* VTracer 引擎封装。
/**
* 描摹引擎:potrace(纯 JS,GPL-2.0)—— 单色 / 灰度分层。
*
* 为什么这么薄:vtracer-wasm 只有 `to_svg(pixels, w, h, config)` 一个入口,
* 参数语义在实测中与官方 CLI 有明显偏差(见 CONFIG_LIMITS),所以把它全部收在这里,
* 上层(ui / trace)只跟「业务参数」打交道。
* 为什么换成 potrace(2026-11-05 用户裁定后的第二版):
* 上一版用 VTracer(彩色分层 + 样条拟合),文字图上会**断笔画、起毛刺、浅色块碎层**,
* 用户实测「看着变矢量但没法用」。potrace 是「二值轮廓追踪 + 曲线拟合」:
* 对 hard edge(文字、logo、线稿)的保形性明显更好,且 turdSize 天生能吃掉小毛刺。
* 代价是它只懂明暗(不懂颜色),所以只做**单色**与**灰度分层**——
* 用户明确说了「单色/灰度就够」,不再做彩色。
*
* 实测得出的三条硬约束(2026-11-05,Chromium + 800×800 合成图扫描):
* 1. colorPrecision 的语义与 vtracer CLI 相反:wasm 侧直接把它当「颜色相似度阈值」
* (is_same_color_a),值越大越容易把不同颜色并成一团。≥6 时整张图会塌成一个色块,
* =8 直接 wasm abort(unreachable)。故夹在 1–5。
* 2. wasm abort 后实例不可再用,且 __wbg_init 见到已有实例会直接返回坏的,
* 所以 panic 后必须 __reset_wasm() 再重建,否则整个插件从此报错。
* 3. 像素必须是 RGBA 四通道(ImageData.data 原样),长度 w*h*4。
* 纯 JS ⇒ 不需要 wasm,**不需要宿主放宽 CSP**(上一版为此加过 'wasm-unsafe-eval',
* 下线时已收回;本版不要再动 CSP)。
*
* 灰度分层为什么自己算阈值:上游 Posterizer 的 `steps` 传数字时会走直方图多级阈值搜索,
* `steps: 5` 实测 28 秒(指数级),完全不可用。改为自己用**等像素量分位**算好阈值数组
* 直接传进去(O(pixels)),5 层也只要几十毫秒。
*/
'use strict'
import init, { to_svg, __reset_wasm } from './vendor/vtracer.js'
import wasmB64 from './vendor/wasm-b64.js'
import Potrace from './vendor/potrace/Potrace.js'
import Posterizer from './vendor/potrace/Posterizer.js'
// colorPrecision 安全区间(见文件头第 1 条)
export const COLOR_PRECISION_MIN = 1
export const COLOR_PRECISION_MAX = 5
export const MODES = ['gray', 'mono']
export const LEVELS_MIN = 2
export const LEVELS_MAX = 5
let wasmBytes = null
let initPromise = null
/** 描摹上限边(超过就降采样):potrace 是纯 JS 单线程,2000px 以上会明显卡主线程 */
export const MAX_TRACE_SIDE = 2000
function decodeWasm() {
if (wasmBytes) return wasmBytes
// 182KB base64 → 137KB 字节;只在首次描摹时解码,避免拖慢插件加载
const bin = atob(wasmB64)
const out = new Uint8Array(bin.length)
for (let i = 0; i < bin.length; i++) out[i] = bin.charCodeAt(i)
wasmBytes = out
return out
export const DEFAULTS = {
mode: 'gray', // 'gray' 灰度分层 / 'mono' 纯单色
levels: 3, // 灰度层数(2–5,仅 gray)
threshold: -1, // -1 = 自动(两种模式都支持)
turdSize: 3, // 去小点:面积小于它的碎片直接丢(毛刺/噪点克星)
alphaMax: 1, // 拐角平滑:0 全折线、1 默认、1.334 最圆
invert: false, // 反相:描摹亮部(黑底白字场景)
color: '#1a1a1a', // mono 的填充色
outScale: 1, // 输出尺寸倍率(只放大尺寸,不重算曲线)
}
function ensureEngine() {
if (!initPromise) {
initPromise = init({ module_or_path: decodeWasm() }).catch(function (error) {
initPromise = null
throw new Error('描摹引擎初始化失败:' + (error && error.message ? error.message : String(error)))
})
}
return initPromise
const clampInt = (v, min, max, dflt) => {
const n = Math.round(Number(v))
return Number.isFinite(n) ? Math.min(max, Math.max(min, n)) : dflt
}
function clampInt(value, min, max, fallback) {
const n = Math.round(Number(value))
if (!Number.isFinite(n)) return fallback
return Math.max(min, Math.min(max, n))
}
/** 业务参数 → wasm config(字段名 camelCase,枚举小写,与结构体字段一一对应) */
export function toEngineConfig(p) {
/** 把 UI / 记忆里的松散参数收敛成引擎能吃的确定值 */
export function normalizeParams(p) {
const src = p || {}
return {
binary: Boolean(p.binary),
mode: p.mode === 'polygon' ? 'polygon' : 'spline',
hierarchical: p.hierarchical === 'cutout' ? 'cutout' : 'stacked',
cornerThreshold: Math.max(0, Math.min(180, Number(p.cornerThreshold) || 60)),
lengthThreshold: Math.max(0.1, Math.min(10, Number(p.lengthThreshold) || 3.5)),
// maxIterations 是曲线拟合的迭代次数。上游 CLI 默认 10,但实测只要 ≥3 就会过拟合抗锯齿边缘:
// 一个正圆被拉成水滴形、圆角矩形的角被吃掉。2 是实测最稳的值(圆保持圆、直角保持直)。
maxIterations: clampInt(p.maxIterations, 1, 10, 2),
spliceThreshold: 45,
filterSpeckle: clampInt(p.filterSpeckle, 0, 128, 4),
// 黑白模式没有颜色聚类,这两个字段只是结构体必填,给安全值即可
colorPrecision: clampInt(p.colorPrecision, COLOR_PRECISION_MIN, COLOR_PRECISION_MAX, 2),
layerDifference: clampInt(p.layerDifference, 0, 64, 16),
pathPrecision: 8,
mode: src.mode === 'mono' ? 'mono' : 'gray',
levels: clampInt(src.levels, LEVELS_MIN, LEVELS_MAX, DEFAULTS.levels),
threshold: Number(src.threshold) >= 0 ? clampInt(src.threshold, 0, 255, 128) : -1,
turdSize: clampInt(src.turdSize, 0, 64, DEFAULTS.turdSize),
alphaMax: (() => {
const n = Number(src.alphaMax)
return Number.isFinite(n) ? Math.min(1.334, Math.max(0, n)) : DEFAULTS.alphaMax
})(),
invert: Boolean(src.invert),
color: /^#[0-9a-f]{6}$/i.test(String(src.color || '')) ? String(src.color) : DEFAULTS.color,
outScale: Math.min(4, Math.max(1, Number(src.outScale) || 1)),
}
}
/**
* 描摹一次。
* @param {Uint8ClampedArray|Uint8Array} rgba 长度必须等于 w*h*4
* @returns {Promise<{svg: string, ms: number}>}
* 等像素量分位阈值:把亮度直方图按像素数切成 levels 段,返回 levels-1 个切点。
*
* 两个必须处理的坑(实测,不是理论问题):
* 1. **主背景色要排除在人口统计之外**。电商图/菜单图里底色常占 60–80% 像素,
* 不排除的话三个切点里有两个会落在背景里,文字还是跟背景分不开(等于没分层)。
* 2. **切点必须严格递增**。背景是一个巨大的尖峰,多个切点会算出同一个亮度值,
* 去重后层数变少(Posterizer 还会算出 0 透明度,整层消失)。
*/
export async function tracePixels(rgba, width, height, params) {
const w = Math.round(width)
const h = Math.round(height)
if (!(w > 0) || !(h > 0)) throw new Error('图片尺寸无效')
if (!rgba || rgba.length !== w * h * 4) throw new Error('像素数据长度与尺寸不符')
await ensureEngine()
const config = toEngineConfig(params)
const pixels = rgba instanceof Uint8Array ? rgba : new Uint8Array(rgba.buffer, rgba.byteOffset, rgba.length)
const started = (typeof performance !== 'undefined' ? performance.now() : Date.now())
try {
const svg = to_svg(pixels, w, h, config)
const ms = Math.round((typeof performance !== 'undefined' ? performance.now() : Date.now()) - started)
return { svg, ms }
} catch (error) {
// wasm abort 后实例已损坏,必须复位,否则下一次调用还是同一个坏实例
initPromise = null
try { __reset_wasm() } catch (e) { /* 复位本身失败也只能继续抛原始错误 */ }
throw new Error(
'描摹失败(引擎内部异常):' + (error && error.message ? error.message : String(error)) +
'。请调大「颜色精度」的容错或换「黑白」模式重试'
)
function quantileThresholds(imageData, levels) {
const hist = new Uint32Array(256)
const data = imageData.data
let total = 0
for (let i = 0; i < data.length; i += 4) {
const a = data[i + 3] / 255
// 与 potrace 内部一致:透明按白底合成后再算亮度
const r = 255 + (data[i] - 255) * a
const g = 255 + (data[i + 1] - 255) * a
const b = 255 + (data[i + 2] - 255) * a
hist[Math.round(0.299 * r + 0.587 * g + 0.114 * b)]++
total++
}
if (!total) return []
// 1) 排除主背景峰(最常见的那个亮度)
let bg = 0
let bgCount = 0
for (let v = 0; v < 256; v++) if (hist[v] > bgCount) { bgCount = hist[v]; bg = v }
const counted = total - bgCount
// 内容太少(几乎纯色图)就退化成等间距,别硬分层
if (counted < total * 0.02) {
const out = []
for (let k = 1; k < levels; k++) out.push(Math.round((255 * k) / levels))
return out
}
// 2) 在「非背景」像素上取等量分位(背景 bin 当 0 处理,但仍参与 value 轴)
const saved = hist[bg]
hist[bg] = 0
const cuts = []
const per = counted / levels
let acc = 0
let next = per
for (let v = 0; v < 256 && cuts.length < levels - 1; v++) {
acc += hist[v]
while (acc >= next && cuts.length < levels - 1) {
cuts.push(v)
next += per
}
}
hist[bg] = saved
// 3) 强制严格递增 + 留出余量(相邻层差至少 1 个亮度级)
const out = []
for (const c of cuts) {
let v = c
if (out.length && v <= out[out.length - 1]) v = out[out.length - 1] + 1
if (v > 254) break
out.push(v)
}
return out
}
/**
* 描摹主入口(同步)。
* @param {{width:number,height:number,data:Uint8ClampedArray}} imageData
* @param {object} params
* @returns {{svg:string, ms:number, paths:number, levels:number}}
*/
export function traceImageData(imageData, params) {
const p = normalizeParams(params)
const now = () => (typeof performance !== 'undefined' ? performance.now() : Date.now())
const t0 = now()
let svg = ''
let levels = 1
if (p.mode === 'mono') {
const potrace = new Potrace({
threshold: p.threshold >= 0 ? p.threshold : Potrace.THRESHOLD_AUTO,
turdSize: p.turdSize,
alphaMax: p.alphaMax,
optCurve: true,
optTolerance: 0.2,
blackOnWhite: !p.invert,
color: p.color,
})
potrace.loadImageData(imageData)
svg = potrace.getSVG()
} else {
const cuts = quantileThresholds(imageData, p.levels)
levels = cuts.length + 1
const posterizer = new Posterizer({
// 传数组 ⇒ 跳过上游的直方图多级阈值搜索(那玩意 5 层要 28s)
steps: cuts.length ? cuts : [128],
threshold: p.threshold >= 0 ? p.threshold : Potrace.THRESHOLD_AUTO,
turdSize: p.turdSize,
alphaMax: p.alphaMax,
optCurve: true,
optTolerance: 0.2,
blackOnWhite: !p.invert,
fillStrategy: 'median', // 灰度:每层取该层亮度中位数
color: '#000000', // 灰度靠 fill-opacity 叠出来,底色固定黑
})
posterizer.loadImageData(imageData)
svg = posterizer.getSVG()
}
return { svg, ms: Math.round(now() - t0), paths: (String(svg).match(/<path/g) || []).length, levels }
}
+8 -12
View File
@@ -13,18 +13,14 @@ var __IWB_VECTORIZE_MANIFEST__ = {
apiVersion: 1,
capabilities: ['commands', 'nodeActions', 'canvas', 'canvasWrite'],
settings: {
preset: { type: 'string', default: 'logo' },
binary: { type: 'boolean', default: false },
hierarchical: { type: 'string', default: 'stacked' },
mode: { type: 'string', default: 'spline' },
colorPrecision: { type: 'number', default: 2 },
layerDifference: { type: 'number', default: 16 },
filterSpeckle: { type: 'number', default: 4 },
cornerThreshold: { type: 'number', default: 60 },
lengthThreshold: { type: 'number', default: 3.5 },
maxIterations: { type: 'number', default: 2 },
denoise: { type: 'number', default: 1 },
bg: { type: 'string', default: 'auto' },
preset: { type: 'string', default: 'text' },
mode: { type: 'string', default: 'gray' },
levels: { type: 'number', default: 3 },
threshold: { type: 'number', default: -1 },
turdSize: { type: 'number', default: 3 },
alphaMax: { type: 'number', default: 1 },
invert: { type: 'boolean', default: false },
color: { type: 'string', default: '#1a1a1a' },
outScale: { type: 'number', default: 2 }
},
}
+41 -222
View File
@@ -1,250 +1,72 @@
/* 位图转矢量的业务层:预设、预处理、SVG 规范化、回栅格。
/* 描摹前处理与 SVG 输出工具(与引擎无关的纯工具函数)。
*
* 预处理为什么必要(实测 2026-11-05):单纯调 lengthThreshold / cornerThreshold 抹不掉
* rembg 那种 ±3px 的毛边 —— 引擎会忠实保留每一个像素级抖动。先把图降采样到 1/2~1/4
* (双线性插值天然把毛刺平均掉)再描摹,轮廓才真正变光滑,且耗时同步下降。
* 代价是小字/细节会糊,所以做成可选强度,默认 1x 不做。
* 上一版(VTracer)里的降噪、背景层剔除、viewBox 修补在这里**全部删掉**了:
* - 降噪:potrace 的 turdSize 天生去小点,不需要先降采样糊一遍;
* - 背景层剔除:potrace 按明暗分层,白底自然成为最亮的一层,不再需要删 path;
* - viewBox 修补:potrace 自己就输出 width/height/viewBox(实测),不用二次拼接。
* 留下的只有:读图 → 必要时降采样 → 生成 PNG / 统计。
*/
'use strict'
import { COLOR_PRECISION_MIN, COLOR_PRECISION_MAX } from './engine.js'
import { MAX_TRACE_SIDE } 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) {
/** 读 data URL 成 <img>(走浏览器解码,与画布语义一致) */
export function loadImage(dataUrl) {
return new Promise(function (resolve, reject) {
const img = new Image()
img.onload = function () { resolve(img) }
img.onerror = function () { reject(new Error('图片解码失败')) }
img.src = src
img.src = dataUrl
})
}
/**
* 预处理:按 denoise 倍数降采样(并把超大图夹到 MAX_TRACE_SIDE 内)。
* @returns {{ canvas: HTMLCanvasElement, w: number, h: number, scale: number, clamped: boolean }}
* 准备描摹用的像素:potrace 是单线程纯 JS,超过 MAX_TRACE_SIDE 会明显卡主线程,
* 所以先按长边夹取(**只缩不放**)。
* @returns {{canvas:HTMLCanvasElement, w:number, h:number, srcW:number, srcH:number, clamped:boolean}}
*/
export function prepareSource(img, denoise) {
export function prepareSource(img) {
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 longSide = Math.max(srcW, srcH)
const k = longSide > MAX_TRACE_SIDE ? MAX_TRACE_SIDE / longSide : 1
const w = Math.max(1, Math.round(srcW * k))
const h = Math.max(1, Math.round(srcH * k))
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 }
const ctx = canvas.getContext('2d', { willReadFrequently: true })
ctx.imageSmoothingEnabled = true
ctx.drawImage(img, 0, 0, w, h)
return { canvas, w, h, srcW, srcH, clamped: k < 1 }
}
/**
* 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:,且不污染画布)。 */
/** SVG 字符串 → <img>(导出时把矢量光栅化) */
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.onerror = function () { URL.revokeObjectURL(url); reject(new Error('矢量渲染失败')) }
img.src = url
})
}
/** SVG → 透明底 PNG Blob(outScale 倍超采样,边缘抗锯齿更好) */
/**
* 把矢量结果光栅化成 PNG(保存为节点用)。outScale 只影响像素尺寸 ——
* 曲线按 viewBox 缩放渲染,所以 2× 是真的更清晰,不是插值放大。
*/
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 k = Math.max(1, Math.min(4, Number(outScale) || 1))
const w = Math.max(1, Math.round(baseW * k))
const h = Math.max(1, Math.round(baseH * k))
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)
const ctx = canvas.getContext('2d')
ctx.drawImage(img, 0, 0, w, h)
return new Promise(function (resolve, reject) {
canvas.toBlob(function (blob) {
if (blob) resolve(blob)
@@ -253,16 +75,13 @@ export async function svgToPngBlob(svg, baseW, baseH, outScale) {
})
}
/** 统计:路径数、文件体积、颜色数 —— 面板底部展示,让「参数调大了会怎样」可见 */
/** 统计:路径数、填充色数、字节数(面板上「体积」那个数字) */
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
const text = String(svg)
const paths = (text.match(/<path/g) || []).length
const fills = []
const re = /fill="([^"]+)"/g
let m
while ((m = re.exec(text))) if (fills.indexOf(m[1]) < 0) fills.push(m[1])
return { paths: paths, colors: fills.length, bytes: text.length }
}
+21
View File
@@ -230,6 +230,10 @@
/* 分段控件 */
.vz-row { margin-bottom: 11px; }
/* 按模式隐藏的行(层数只在灰度、阈值只在手动)必须真的消失。
踩过的坑:flex/块级元素上加 `hidden` 属性,如果 CSS 里另有 display 声明就会失效,
于是「隐藏」只变成视觉上还在 —— 这里直接 !important 兜住所有形态。 */
.vz-row[hidden] { display: none !important; }
.vz-row:last-child { margin-bottom: 0; }
.vz-row-label {
@@ -323,6 +327,23 @@
.vz-adv-toggle:hover { background: #2c2c38; color: #d0d0e0; }
.vz-adv-toggle span { color: #6f6f85; }
/* 单色填充色(仅「纯单色」生效)。原生 color input 在深色面板里默认边框很亮,
去掉内边距与外框,只留一块颜色本身,和滑杆行视觉一致 */
.vz-color {
flex: 0 0 auto;
width: 42px;
height: 22px;
padding: 0;
border: 1px solid #45455a;
border-radius: 6px;
background: transparent;
cursor: pointer;
}
.vz-color::-webkit-color-swatch-wrapper { padding: 2px; }
.vz-color::-webkit-color-swatch { border: none; border-radius: 4px; }
.vz-color:disabled { cursor: default; }
.vz-adv { margin-top: 10px; }
.vz-adv[hidden] { display: none; }
+157 -144
View File
@@ -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)
-21
View File
@@ -1,21 +0,0 @@
MIT License
Copyright (c) 2025 jsscheller
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
+339
View File
@@ -0,0 +1,339 @@
GNU GENERAL PUBLIC LICENSE
Version 2, June 1991
Copyright (C) 1989, 1991 Free Software Foundation, Inc., <http://fsf.org/>
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
Preamble
The licenses for most software are designed to take away your
freedom to share and change it. By contrast, the GNU General Public
License is intended to guarantee your freedom to share and change free
software--to make sure the software is free for all its users. This
General Public License applies to most of the Free Software
Foundation's software and to any other program whose authors commit to
using it. (Some other Free Software Foundation software is covered by
the GNU Lesser General Public License instead.) You can apply it to
your programs, too.
When we speak of free software, we are referring to freedom, not
price. Our General Public Licenses are designed to make sure that you
have the freedom to distribute copies of free software (and charge for
this service if you wish), that you receive source code or can get it
if you want it, that you can change the software or use pieces of it
in new free programs; and that you know you can do these things.
To protect your rights, we need to make restrictions that forbid
anyone to deny you these rights or to ask you to surrender the rights.
These restrictions translate to certain responsibilities for you if you
distribute copies of the software, or if you modify it.
For example, if you distribute copies of such a program, whether
gratis or for a fee, you must give the recipients all the rights that
you have. You must make sure that they, too, receive or can get the
source code. And you must show them these terms so they know their
rights.
We protect your rights with two steps: (1) copyright the software, and
(2) offer you this license which gives you legal permission to copy,
distribute and/or modify the software.
Also, for each author's protection and ours, we want to make certain
that everyone understands that there is no warranty for this free
software. If the software is modified by someone else and passed on, we
want its recipients to know that what they have is not the original, so
that any problems introduced by others will not reflect on the original
authors' reputations.
Finally, any free program is threatened constantly by software
patents. We wish to avoid the danger that redistributors of a free
program will individually obtain patent licenses, in effect making the
program proprietary. To prevent this, we have made it clear that any
patent must be licensed for everyone's free use or not licensed at all.
The precise terms and conditions for copying, distribution and
modification follow.
GNU GENERAL PUBLIC LICENSE
TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
0. This License applies to any program or other work which contains
a notice placed by the copyright holder saying it may be distributed
under the terms of this General Public License. The "Program", below,
refers to any such program or work, and a "work based on the Program"
means either the Program or any derivative work under copyright law:
that is to say, a work containing the Program or a portion of it,
either verbatim or with modifications and/or translated into another
language. (Hereinafter, translation is included without limitation in
the term "modification".) Each licensee is addressed as "you".
Activities other than copying, distribution and modification are not
covered by this License; they are outside its scope. The act of
running the Program is not restricted, and the output from the Program
is covered only if its contents constitute a work based on the
Program (independent of having been made by running the Program).
Whether that is true depends on what the Program does.
1. You may copy and distribute verbatim copies of the Program's
source code as you receive it, in any medium, provided that you
conspicuously and appropriately publish on each copy an appropriate
copyright notice and disclaimer of warranty; keep intact all the
notices that refer to this License and to the absence of any warranty;
and give any other recipients of the Program a copy of this License
along with the Program.
You may charge a fee for the physical act of transferring a copy, and
you may at your option offer warranty protection in exchange for a fee.
2. You may modify your copy or copies of the Program or any portion
of it, thus forming a work based on the Program, and copy and
distribute such modifications or work under the terms of Section 1
above, provided that you also meet all of these conditions:
a) You must cause the modified files to carry prominent notices
stating that you changed the files and the date of any change.
b) You must cause any work that you distribute or publish, that in
whole or in part contains or is derived from the Program or any
part thereof, to be licensed as a whole at no charge to all third
parties under the terms of this License.
c) If the modified program normally reads commands interactively
when run, you must cause it, when started running for such
interactive use in the most ordinary way, to print or display an
announcement including an appropriate copyright notice and a
notice that there is no warranty (or else, saying that you provide
a warranty) and that users may redistribute the program under
these conditions, and telling the user how to view a copy of this
License. (Exception: if the Program itself is interactive but
does not normally print such an announcement, your work based on
the Program is not required to print an announcement.)
These requirements apply to the modified work as a whole. If
identifiable sections of that work are not derived from the Program,
and can be reasonably considered independent and separate works in
themselves, then this License, and its terms, do not apply to those
sections when you distribute them as separate works. But when you
distribute the same sections as part of a whole which is a work based
on the Program, the distribution of the whole must be on the terms of
this License, whose permissions for other licensees extend to the
entire whole, and thus to each and every part regardless of who wrote it.
Thus, it is not the intent of this section to claim rights or contest
your rights to work written entirely by you; rather, the intent is to
exercise the right to control the distribution of derivative or
collective works based on the Program.
In addition, mere aggregation of another work not based on the Program
with the Program (or with a work based on the Program) on a volume of
a storage or distribution medium does not bring the other work under
the scope of this License.
3. You may copy and distribute the Program (or a work based on it,
under Section 2) in object code or executable form under the terms of
Sections 1 and 2 above provided that you also do one of the following:
a) Accompany it with the complete corresponding machine-readable
source code, which must be distributed under the terms of Sections
1 and 2 above on a medium customarily used for software interchange; or,
b) Accompany it with a written offer, valid for at least three
years, to give any third party, for a charge no more than your
cost of physically performing source distribution, a complete
machine-readable copy of the corresponding source code, to be
distributed under the terms of Sections 1 and 2 above on a medium
customarily used for software interchange; or,
c) Accompany it with the information you received as to the offer
to distribute corresponding source code. (This alternative is
allowed only for noncommercial distribution and only if you
received the program in object code or executable form with such
an offer, in accord with Subsection b above.)
The source code for a work means the preferred form of the work for
making modifications to it. For an executable work, complete source
code means all the source code for all modules it contains, plus any
associated interface definition files, plus the scripts used to
control compilation and installation of the executable. However, as a
special exception, the source code distributed need not include
anything that is normally distributed (in either source or binary
form) with the major components (compiler, kernel, and so on) of the
operating system on which the executable runs, unless that component
itself accompanies the executable.
If distribution of executable or object code is made by offering
access to copy from a designated place, then offering equivalent
access to copy the source code from the same place counts as
distribution of the source code, even though third parties are not
compelled to copy the source along with the object code.
4. You may not copy, modify, sublicense, or distribute the Program
except as expressly provided under this License. Any attempt
otherwise to copy, modify, sublicense or distribute the Program is
void, and will automatically terminate your rights under this License.
However, parties who have received copies, or rights, from you under
this License will not have their licenses terminated so long as such
parties remain in full compliance.
5. You are not required to accept this License, since you have not
signed it. However, nothing else grants you permission to modify or
distribute the Program or its derivative works. These actions are
prohibited by law if you do not accept this License. Therefore, by
modifying or distributing the Program (or any work based on the
Program), you indicate your acceptance of this License to do so, and
all its terms and conditions for copying, distributing or modifying
the Program or works based on it.
6. Each time you redistribute the Program (or any work based on the
Program), the recipient automatically receives a license from the
original licensor to copy, distribute or modify the Program subject to
these terms and conditions. You may not impose any further
restrictions on the recipients' exercise of the rights granted herein.
You are not responsible for enforcing compliance by third parties to
this License.
7. If, as a consequence of a court judgment or allegation of patent
infringement or for any other reason (not limited to patent issues),
conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License. If you cannot
distribute so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you
may not distribute the Program at all. For example, if a patent
license would not permit royalty-free redistribution of the Program by
all those who receive copies directly or indirectly through you, then
the only way you could satisfy both it and this License would be to
refrain entirely from distribution of the Program.
If any portion of this section is held invalid or unenforceable under
any particular circumstance, the balance of the section is intended to
apply and the section as a whole is intended to apply in other
circumstances.
It is not the purpose of this section to induce you to infringe any
patents or other property right claims or to contest validity of any
such claims; this section has the sole purpose of protecting the
integrity of the free software distribution system, which is
implemented by public license practices. Many people have made
generous contributions to the wide range of software distributed
through that system in reliance on consistent application of that
system; it is up to the author/donor to decide if he or she is willing
to distribute software through any other system and a licensee cannot
impose that choice.
This section is intended to make thoroughly clear what is believed to
be a consequence of the rest of this License.
8. If the distribution and/or use of the Program is restricted in
certain countries either by patents or by copyrighted interfaces, the
original copyright holder who places the Program under this License
may add an explicit geographical distribution limitation excluding
those countries, so that distribution is permitted only in or among
countries not thus excluded. In such case, this License incorporates
the limitation as if written in the body of this License.
9. The Free Software Foundation may publish revised and/or new versions
of the General Public License from time to time. Such new versions will
be similar in spirit to the present version, but may differ in detail to
address new problems or concerns.
Each version is given a distinguishing version number. If the Program
specifies a version number of this License which applies to it and "any
later version", you have the option of following the terms and conditions
either of that version or of any later version published by the Free
Software Foundation. If the Program does not specify a version number of
this License, you may choose any version ever published by the Free Software
Foundation.
10. If you wish to incorporate parts of the Program into other free
programs whose distribution conditions are different, write to the author
to ask for permission. For software which is copyrighted by the Free
Software Foundation, write to the Free Software Foundation; we sometimes
make exceptions for this. Our decision will be guided by the two goals
of preserving the free status of all derivatives of our free software and
of promoting the sharing and reuse of software generally.
NO WARRANTY
11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY
FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN
OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES
PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED
OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS
TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE
PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING,
REPAIR OR CORRECTION.
12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR
REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES,
INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING
OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED
TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY
YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER
PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE
POSSIBILITY OF SUCH DAMAGES.
END OF TERMS AND CONDITIONS
How to Apply These Terms to Your New Programs
If you develop a new program, and you want it to be of the greatest
possible use to the public, the best way to achieve this is to make it
free software which everyone can redistribute and change under these terms.
To do so, attach the following notices to the program. It is safest
to attach them to the start of each source file to most effectively
convey the exclusion of warranty; and each file should have at least
the "copyright" line and a pointer to where the full notice is found.
{description}
Copyright (C) {year} {fullname}
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License along
with this program; if not, write to the Free Software Foundation, Inc.,
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
Also add information on how to contact you by electronic and paper mail.
If the program is interactive, make it output a short notice like this
when it starts in an interactive mode:
Gnomovision version 69, Copyright (C) year name of author
Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
This is free software, and you are welcome to redistribute it
under certain conditions; type `show c' for details.
The hypothetical commands `show w' and `show c' should show the appropriate
parts of the General Public License. Of course, the commands you use may
be called something other than `show w' and `show c'; they could even be
mouse-clicks or menu items--whatever suits your program.
You should also get your employer (if you work as a programmer) or your
school, if any, to sign a "copyright disclaimer" for the program, if
necessary. Here is a sample; alter the names:
Yoyodyne, Inc., hereby disclaims all copyright interest in the program
`Gnomovision' (which makes passes at compilers) written by James Hacker.
{signature of Ty Coon}, 1 April 1989
Ty Coon, President of Vice
This General Public License does not permit incorporating your program into
proprietary programs. If your program is a subroutine library, you may
consider it more useful to permit linking proprietary applications with the
library. If this is what you want to do, use the GNU Lesser General
Public License instead of this License.
+458
View File
@@ -0,0 +1,458 @@
'use strict';
var Potrace = require('./Potrace');
var utils = require('./utils');
/**
* Takes multiple samples using {@link Potrace} with different threshold
* settings and combines output into a single file.
*
* @param {Posterizer~Options} [options]
* @constructor
*/
function Posterizer(options) {
this._potrace = new Potrace();
this._calculatedThreshold = null;
this._params = {
threshold: Potrace.THRESHOLD_AUTO,
blackOnWhite: true,
steps: Posterizer.STEPS_AUTO,
background: Potrace.COLOR_TRANSPARENT,
fillStrategy: Posterizer.FILL_DOMINANT,
rangeDistribution: Posterizer.RANGES_AUTO
};
if (options) {
this.setParameters(options);
}
}
// Inherit constants from Potrace class
for (var key in Potrace) {
if (Object.prototype.hasOwnProperty.call(Potrace, key) && key === key.toUpperCase()) {
Posterizer[key] = Potrace[key];
}
}
Posterizer.STEPS_AUTO = -1;
Posterizer.FILL_SPREAD = 'spread';
Posterizer.FILL_DOMINANT = 'dominant';
Posterizer.FILL_MEDIAN = 'median';
Posterizer.FILL_MEAN = 'mean';
Posterizer.RANGES_AUTO = 'auto';
Posterizer.RANGES_EQUAL = 'equal';
Posterizer.prototype = {
/**
* Fine tuning to color ranges.
*
* If last range (featuring most saturated color) is larger than 10% of color space (25 units)
* then we want to add another color stop, that hopefully will include darkest pixels, improving presence of
* shadows and line art
*
* @param ranges
* @private
*/
_addExtraColorStop: function(ranges) {
var blackOnWhite = this._params.blackOnWhite;
var lastColorStop = ranges[ranges.length - 1];
var lastRangeFrom = blackOnWhite ? 0 : lastColorStop.value;
var lastRangeTo = blackOnWhite ? lastColorStop.value : 255;
if (lastRangeTo - lastRangeFrom > 25 && lastColorStop.colorIntensity !== 1) {
var histogram = this._getImageHistogram();
var levels = histogram.getStats(lastRangeFrom, lastRangeTo).levels;
var newColorStop = levels.mean + levels.stdDev <= 25 ? levels.mean + levels.stdDev
: levels.mean - levels.stdDev <= 25 ? levels.mean - levels.stdDev
: 25;
var newStats = (blackOnWhite ? histogram.getStats(0, newColorStop) : histogram.getStats(newColorStop, 255));
var color = newStats.levels.mean;
ranges.push({
value: Math.abs((blackOnWhite ? 0 : 255) - newColorStop),
colorIntensity: isNaN(color) ? 0 : ((blackOnWhite ? 255 - color : color) / 255)
});
}
return ranges;
},
/**
* Calculates color intensity for each element of numeric array
*
* @param {number[]} colorStops
* @returns {{ levels: number, colorIntensity: number }[]}
* @private
*/
_calcColorIntensity: function(colorStops) {
var blackOnWhite = this._params.blackOnWhite;
var colorSelectionStrat = this._params.fillStrategy;
var histogram = colorSelectionStrat !== Posterizer.FILL_SPREAD ? this._getImageHistogram() : null;
var fullRange = Math.abs(this._paramThreshold() - (blackOnWhite ? 0 : 255));
return colorStops.map(function(threshold, index) {
var nextValue = index + 1 === colorStops.length ? (blackOnWhite ? -1 : 256) : colorStops[index + 1];
var rangeStart = Math.round(blackOnWhite ? nextValue + 1 : threshold);
var rangeEnd = Math.round(blackOnWhite ? threshold : nextValue - 1);
var factor = index / (colorStops.length - 1);
var intervalSize = rangeEnd - rangeStart;
var stats = histogram.getStats(rangeStart, rangeEnd);
var color = -1;
if (stats.pixels === 0) {
return {
value: threshold,
colorIntensity: 0
};
}
switch (colorSelectionStrat) {
case Posterizer.FILL_SPREAD:
// We want it to be 0 (255 when white on black) at the most saturated end, so...
color = (blackOnWhite ? rangeStart : rangeEnd)
+ (blackOnWhite ? 1 : -1) * intervalSize * Math.max(0.5, fullRange / 255) * factor;
break;
case Posterizer.FILL_DOMINANT:
color = histogram.getDominantColor(rangeStart, rangeEnd, utils.clamp(intervalSize, 1, 5));
break;
case Posterizer.FILL_MEAN:
color = stats.levels.mean;
break;
case Posterizer.FILL_MEDIAN:
color = stats.levels.median;
break;
}
// We don't want colors to be too close to each other, so we introduce some spacing in between
if (index !== 0) {
color = blackOnWhite
? utils.clamp(color, rangeStart, rangeEnd - Math.round(intervalSize * 0.1))
: utils.clamp(color, rangeStart + Math.round(intervalSize * 0.1), rangeEnd);
}
return {
value: threshold,
colorIntensity: color === -1 ? 0 : ((blackOnWhite ? 255 - color : color) / 255)
};
});
},
/**
* @returns {Histogram}
* @private
*/
_getImageHistogram: function() {
return this._potrace._luminanceData.histogram();
},
/**
* Processes threshold, steps and rangeDistribution parameters and returns normalized array of color stops
* @returns {*}
* @private
*/
_getRanges: function() {
var steps = this._paramSteps();
if (!Array.isArray(steps)) {
return this._params.rangeDistribution === Posterizer.RANGES_AUTO
? this._getRangesAuto()
: this._getRangesEquallyDistributed();
}
// Steps is array of thresholds and we want to preprocess it
var colorStops = [];
var threshold = this._paramThreshold();
var lookingForDarkPixels = this._params.blackOnWhite;
steps.forEach(function(item) {
if (colorStops.indexOf(item) === -1 && utils.between(item, 0, 255)) {
colorStops.push(item);
}
});
if (!colorStops.length) {
colorStops.push(threshold);
}
colorStops = colorStops.sort(function (a, b) {
return a < b === lookingForDarkPixels ? 1 : -1;
});
if (lookingForDarkPixels && colorStops[0] < threshold) {
colorStops.unshift(threshold);
} else if (!lookingForDarkPixels && colorStops[colorStops.length - 1] < threshold) {
colorStops.push(threshold);
}
return this._calcColorIntensity(colorStops);
},
/**
* Calculates given (or lower) number of thresholds using automatic thresholding algorithm
* @returns {*}
* @private
*/
_getRangesAuto: function() {
var histogram = this._getImageHistogram();
var steps = this._paramSteps(true);
var colorStops;
if (this._params.threshold === Potrace.THRESHOLD_AUTO) {
colorStops = histogram.multilevelThresholding(steps);
} else {
var threshold = this._paramThreshold();
colorStops = this._params.blackOnWhite
? histogram.multilevelThresholding(steps - 1, 0, threshold)
: histogram.multilevelThresholding(steps - 1, threshold, 255);
if (this._params.blackOnWhite) {
colorStops.push(threshold);
} else {
colorStops.unshift(threshold);
}
}
if (this._params.blackOnWhite) {
colorStops = colorStops.reverse();
}
return this._calcColorIntensity(colorStops);
},
/**
* Calculates color stops and color representing each segment, returning them
* from least to most intense color (black or white, depending on blackOnWhite parameter)
*
* @private
*/
_getRangesEquallyDistributed: function() {
var blackOnWhite = this._params.blackOnWhite;
var colorsToThreshold = blackOnWhite ? this._paramThreshold() : 255 - this._paramThreshold();
var steps = this._paramSteps();
var stepSize = colorsToThreshold / steps;
var colorStops = [];
var i = steps - 1,
factor,
threshold;
while (i >= 0) {
factor = i / (steps - 1);
threshold = Math.min(colorsToThreshold, (i + 1) * stepSize);
threshold = blackOnWhite ? threshold : 255 - threshold;
i--;
colorStops.push(threshold);
}
return this._calcColorIntensity(colorStops);
},
/**
* Returns valid steps value
* @param {Boolean} [count=false]
* @returns {number|number[]}
* @private
*/
_paramSteps: function(count) {
var steps = this._params.steps;
if (Array.isArray(steps)) {
return count ? steps.length : steps;
}
if (steps === Posterizer.STEPS_AUTO && this._params.threshold === Potrace.THRESHOLD_AUTO) {
return 4;
}
var blackOnWhite = this._params.blackOnWhite;
var colorsCount = blackOnWhite ? this._paramThreshold() : 255 - this._paramThreshold();
return steps === Posterizer.STEPS_AUTO
? (colorsCount > 200 ? 4 : 3)
: Math.min(colorsCount, Math.max(2, steps));
},
/**
* Returns valid threshold value
* @returns {number}
* @private
*/
_paramThreshold: function() {
if (this._calculatedThreshold !== null) {
return this._calculatedThreshold;
}
if (this._params.threshold !== Potrace.THRESHOLD_AUTO) {
this._calculatedThreshold = this._params.threshold;
return this._calculatedThreshold;
}
var twoThresholds = this._getImageHistogram().multilevelThresholding(2);
this._calculatedThreshold = this._params.blackOnWhite ? twoThresholds[1] : twoThresholds[0];
this._calculatedThreshold = this._calculatedThreshold || 128;
return this._calculatedThreshold;
},
/**
* Running potrace on the image multiple times with different thresholds and returns an array
* of path tags
*
* @param {Boolean} [noFillColor]
* @returns {string[]}
* @private
*/
_pathTags: function(noFillColor) {
var ranges = this._getRanges();
var potrace = this._potrace;
var blackOnWhite = this._params.blackOnWhite;
if (ranges.length >= 10) {
ranges = this._addExtraColorStop(ranges);
}
potrace.setParameters({ blackOnWhite: blackOnWhite });
var actualPrevLayersOpacity = 0;
return ranges.map(function(colorStop) {
var thisLayerOpacity = colorStop.colorIntensity;
if (thisLayerOpacity === 0) {
return '';
}
// NOTE: With big number of layers (something like 70) there will be noticeable math error on rendering side.
// In Chromium at least image will end up looking brighter overall compared to the same layers painted in solid colors.
// However it works fine with sane number of layers, and it's not like we can do much about it.
var calculatedOpacity = (!actualPrevLayersOpacity || thisLayerOpacity === 1)
? thisLayerOpacity
: ((actualPrevLayersOpacity - thisLayerOpacity) / (actualPrevLayersOpacity - 1));
calculatedOpacity = utils.clamp(parseFloat(calculatedOpacity.toFixed(3)), 0, 1);
actualPrevLayersOpacity = actualPrevLayersOpacity + (1 - actualPrevLayersOpacity) * calculatedOpacity;
potrace.setParameters({ threshold: colorStop.value });
var element = noFillColor ? potrace.getPathTag('') : potrace.getPathTag();
element = utils.setHtmlAttr(element, 'fill-opacity', calculatedOpacity.toFixed(3));
var canBeIgnored = calculatedOpacity === 0 || element.indexOf(' d=""') !== -1;
// var c = Math.round(Math.abs((blackOnWhite ? 255 : 0) - 255 * thisLayerOpacity));
// element = utils.setHtmlAttr(element, 'fill', 'rgb('+c+', '+c+', '+c+')');
// element = utils.setHtmlAttr(element, 'fill-opacity', '');
return canBeIgnored ? '' : element;
});
},
/**
* Loads image.
*
* @param {string|Buffer|Jimp} target Image source. Could be anything that {@link Jimp} can read (buffer, local path or url). Supported formats are: PNG, JPEG or BMP
* @param {Function} callback
*/
loadImage: function(target, callback) {
var self = this;
this._potrace.loadImage(target, function(err) {
self._calculatedThreshold = null;
callback.call(self, err);
});
},
/**
* 本项目新增:直接吃浏览器 ImageData(同步),与 Potrace#loadImageData 对应。
* 灰度分层不需要异步读图 ⇒ 调用方拿到的就是同步结果,省掉一层回调。
*/
loadImageData: function(imageData) {
this._potrace.loadImageData(imageData);
this._calculatedThreshold = null;
},
/**
* Sets parameters. Accepts same object as {Potrace}
*
* @param {Posterizer~Options} params
*/
setParameters: function(params) {
if (!params) {
return;
}
this._potrace.setParameters(params);
if (params.steps && !Array.isArray(params.steps) && (!utils.isNumber(params.steps) || !utils.between(params.steps, 1, 255))) {
throw new Error('Bad \'steps\' value');
}
for (var key in this._params) {
if (this._params.hasOwnProperty(key) && params.hasOwnProperty(key)) {
this._params[key] = params[key];
}
}
this._calculatedThreshold = null;
},
/**
* Returns image as <symbol> tag. Always has viewBox specified
*
* @param {string} id
*/
getSymbol: function(id) {
var width = this._potrace._luminanceData.width;
var height = this._potrace._luminanceData.height;
var paths = this._pathTags(true);
return '<symbol viewBox="0 0 ' + width + ' ' + height + '" id="' + id + '">' +
paths.join('') +
'</symbol>';
},
/**
* Generates SVG image
* @returns {String}
*/
getSVG: function() {
var width = this._potrace._luminanceData.width,
height = this._potrace._luminanceData.height;
var tags = this._pathTags(false);
var svg = '<svg xmlns="http://www.w3.org/2000/svg" ' +
'width="' + width + '" ' +
'height="' + height + '" ' +
'viewBox="0 0 ' + width + ' ' + height + '" ' +
'version="1.1">\n\t' +
(this._params.background !== Potrace.COLOR_TRANSPARENT
? '<rect x="0" y="0" width="100%" height="100%" fill="' + this._params.background + '" />\n\t'
: '') +
tags.join('\n\t') +
'\n</svg>';
return svg.replace(/\n(?:\t*\n)+(\t*)/g, '\n$1');
}
};
module.exports = Posterizer;
/**
* Posterizer options
*
* @typedef {Potrace~Options} Posterizer~Options
* @property {Number} [steps] - Number of samples that needs to be taken (and number of layers in SVG). (default: Posterizer.STEPS_AUTO, which most likely will result in 3, sometimes 4)
* @property {*} [fillStrategy] - How to select fill color for color ranges - equally spread or dominant. (default: Posterizer.FILL_DOMINANT)
* @property {*} [rangeDistribution] - How to choose thresholds in-between - after equal intervals or automatically balanced. (default: Posterizer.RANGES_AUTO)
*/
File diff suppressed because it is too large. Load diff
+111
View File
@@ -0,0 +1,111 @@
'use strict';
var Point = require('./Point');
var utils = require('../utils');
var Histogram;
/**
* Represents a bitmap where each pixel can be a number in range of 0..255
* Used internally to store luminance data.
*
* @param {Number} w
* @param {Number} h
* @constructor
*/
function Bitmap(w, h) {
this._histogram = null;
this.width = w;
this.height = h;
this.size = w * h;
this.arrayBuffer = new ArrayBuffer(this.size);
this.data = new Uint8Array(this.arrayBuffer);
}
module.exports = Bitmap;
Histogram = require('./Histogram');
Bitmap.prototype = {
/**
* Returns pixel value
*
* @param {Number|Point} x - index, point or x
* @param {Number} [y]
*/
getValueAt: function(x, y) {
var index = (typeof x === 'number' && typeof y !== 'number') ? x : this.pointToIndex(x, y);
return this.data[index];
},
/**
* Converts {@link Point} to index value
*
* @param {Number} index
* @returns {Point}
*/
indexToPoint: function(index) {
var point = new Point();
if (utils.between(index, 0, this.size)) {
point.y = Math.floor(index / this.width);
point.x = index - point.y * this.width;
} else {
point.x = -1;
point.y = -1;
}
return point;
},
/**
* Calculates index for point or coordinate pair
*
* @param {Number|Point} pointOrX
* @param {Number} [y]
* @returns {Number}
*/
pointToIndex: function(pointOrX, y) {
var _x = pointOrX,
_y = y;
if (pointOrX instanceof Point) {
_x = pointOrX.x;
_y = pointOrX.y;
}
if (!utils.between(_x, 0, this.width) || !utils.between(_y, 0, this.height)) {
return -1;
}
return this.width * _y + _x;
},
/**
* Makes a copy of current bitmap
*
* @param {Function} [iterator] optional callback, used for processing pixel value. Accepted arguments: value, index
* @returns {Bitmap}
*/
copy: function(iterator) {
var bm = new Bitmap(this.width, this.height),
iteratorPresent = typeof iterator === 'function',
i;
for (i = 0; i < this.size; i++) {
bm.data[i] = iteratorPresent ? iterator(this.data[i], i) : this.data[i];
}
return bm;
},
histogram: function() {
var Histogram = require('./Histogram');
if (this._histogram) {
return this._histogram;
}
this._histogram = new Histogram(this);
return this._histogram;
}
};
+21
View File
@@ -0,0 +1,21 @@
'use strict';
/**
* Curve type
*
* @param n
* @constructor
* @protected
*/
function Curve(n) {
this.n = n;
this.tag = new Array(n);
this.c = new Array(n * 3);
this.alphaCurve = 0;
this.vertex = new Array(n);
this.alpha = new Array(n);
this.alpha0 = new Array(n);
this.beta = new Array(n);
}
module.exports = Curve;
+425
View File
@@ -0,0 +1,425 @@
"use strict";
// Histogram
var utils = require('../utils');
var Jimp = null; try { Jimp = require('jimp'); } catch(e) {}
var Bitmap = require('./Bitmap');
var COLOR_DEPTH = 256;
var COLOR_RANGE_END = COLOR_DEPTH - 1;
/**
* Calculates array index for pair of indexes. We multiple column (x) by 256 and then add row to it,
* this way `(index(i, j) + 1) === index(i, j + i)` thus we can reuse `index(i, j)` we once calculated
*
* Note: this is different from how indexes calculated in {@link Bitmap} class, keep it in mind.
*
* @param x
* @param y
* @returns {*}
* @private
*/
function index(x, y) {
return COLOR_DEPTH * x + y;
}
function normalizeMinMax(levelMin, levelMax) {
/**
* Shared parameter normalization for methods 'multilevelThresholding', 'autoThreshold', 'getDominantColor' and 'getStats'
*
* @param levelMin
* @param levelMax
* @returns {number[]}
* @private
*/
levelMin = typeof levelMin === 'number' ? utils.clamp(Math.round(levelMin), 0, COLOR_RANGE_END) : 0;
levelMax = typeof levelMax === 'number' ? utils.clamp(Math.round(levelMax), 0, COLOR_RANGE_END) : COLOR_RANGE_END;
if (levelMin > levelMax) {
throw new Error('Invalid range "'+ levelMin + '...' + levelMax + '"');
}
return [levelMin, levelMax];
}
/**
* 1D Histogram
*
* @param {Number|Bitmap|Jimp} imageSource - Image to collect pixel data from. Or integer to create empty histogram for image of specific size
* @param [mode] Used only for Jimp images. {@link Bitmap} currently can only store 256 values per pixel, so it's assumed that it contains values we are looking for
* @constructor
* @protected
*/
function Histogram(imageSource, mode) {
this.data = null;
this.pixels = 0;
this._sortedIndexes = null;
this._cachedStats = {};
this._lookupTableH = null;
if (typeof imageSource === 'number') {
this._createArray(imageSource);
} else if (imageSource instanceof Bitmap) {
this._collectValuesBitmap(imageSource);
} else if (Jimp && imageSource instanceof Jimp) {
this._collectValuesJimp(imageSource, mode);
} else {
throw new Error('Unsupported image source');
}
}
Histogram.MODE_LUMINANCE = 'luminance';
Histogram.MODE_R = 'r';
Histogram.MODE_G = 'g';
Histogram.MODE_B = 'b';
Histogram.prototype = {
/**
* Initializes data array for an image of given pixel size
* @param imageSize
* @returns {Uint8Array|Uint16Array|Uint32Array}
* @private
*/
_createArray: function(imageSize) {
var ArrayType = imageSize <= Math.pow(2, 8) ? Uint8Array
: imageSize <= Math.pow(2, 16) ? Uint16Array : Uint32Array;
this.pixels = imageSize;
return this.data = new ArrayType(COLOR_DEPTH);
},
/**
* Aggregates color data from {@link Jimp} instance
* @param {Jimp} source
* @param mode
* @private
*/
_collectValuesJimp: function(source, mode) {
var pixelData = source.bitmap.data;
var data = this._createArray(source.bitmap.width * source.bitmap.height);
source.scan(0, 0, source.bitmap.width, source.bitmap.height, function(x, y, idx) {
var val = mode === Histogram.MODE_R ? pixelData[idx]
: mode === Histogram.MODE_G ? pixelData[idx + 1]
: mode === Histogram.MODE_B ? pixelData[idx + 2]
: utils.luminance(pixelData[idx], pixelData[idx + 1], pixelData[idx + 2]);
data[val]++;
});
},
/**
* Aggregates color data from {@link Bitmap} instance
* @param {Bitmap} source
* @private
*/
_collectValuesBitmap: function(source) {
var data = this._createArray(source.size);
var len = source.data.length;
var color;
for (var i = 0; i < len; i++) {
color = source.data[i];
data[color]++
}
},
/**
* Returns array of color indexes in ascending order
* @param refresh
* @returns {*}
* @private
*/
_getSortedIndexes: function(refresh) {
if (!refresh && this._sortedIndexes) {
return this._sortedIndexes;
}
var data = this.data;
var indexes = new Array(COLOR_DEPTH);
var i = 0;
for (i; i < COLOR_DEPTH; i++) {
indexes[i] = i;
}
indexes.sort(function(a, b) {
return data[a] > data[b] ? 1 : data[a] < data[b] ? -1 : 0;
});
this._sortedIndexes = indexes;
return indexes;
},
/**
* Builds lookup table H from lookup tables P and S.
* see {@link http://www.iis.sinica.edu.tw/page/jise/2001/200109_01.pdf|this paper} for more details
*
* @returns {Float64Array}
* @private
*/
_thresholdingBuildLookupTable: function() {
var P = new Float64Array(COLOR_DEPTH * COLOR_DEPTH);
var S = new Float64Array(COLOR_DEPTH * COLOR_DEPTH);
var H = new Float64Array(COLOR_DEPTH * COLOR_DEPTH);
var pixelsTotal = this.pixels;
var i, j, idx, tmp;
// diagonal
for (i = 1; i < COLOR_DEPTH; ++i) {
idx = index(i, i);
tmp = this.data[i] / pixelsTotal;
P[idx] = tmp;
S[idx] = i * tmp;
}
// calculate first row (row 0 is all zero)
for (i = 1; i < COLOR_DEPTH - 1; ++i) {
tmp = this.data[i + 1] / pixelsTotal;
idx = index(1, i);
P[idx+1] = P[idx] + tmp;
S[idx+1] = S[idx] + (i + 1) * tmp;
}
// using row 1 to calculate others
for (i = 2; i < COLOR_DEPTH; i++) {
for (j=i+1; j < COLOR_DEPTH; j++) {
P[index(i, j)] = P[index(1, j)] - P[index(1, i-1)];
S[index(i, j)] = S[index(1, j)] - S[index(1, i-1)];
}
}
// now calculate H[i][j]
for (i = 1; i < COLOR_DEPTH; ++i) {
for (j = i + 1; j < COLOR_DEPTH; j++) {
idx = index(i, j);
H[idx] = P[idx] !== 0 ? S[idx] * S[idx] / P[idx] : 0;
}
}
return this._lookupTableH = H;
},
/**
* Implements Algorithm For Multilevel Thresholding
* Receives desired number of color stops, returns array of said size. Could be limited to a range levelMin..levelMax
*
* Regardless of levelMin and levelMax values it still relies on between class variances for the entire histogram
*
* @param amount - how many thresholds should be calculated
* @param [levelMin=0] - histogram segment start
* @param [levelMax=255] - histogram segment end
* @returns {number[]}
*/
multilevelThresholding: function (amount, levelMin, levelMax) {
levelMin = normalizeMinMax(levelMin, levelMax);
levelMax = levelMin[1];
levelMin = levelMin[0];
amount = Math.min(levelMax - levelMin - 2, ~~amount);
if (amount < 1) {
return [];
}
if (!this._lookupTableH) {
this._thresholdingBuildLookupTable();
}
var H = this._lookupTableH;
var colorStops = null;
var maxSig = 0;
if (amount > 4) {
console.log('[Warning]: Threshold computation for more than 5 levels may take a long time');
}
function iterateRecursive (startingPoint, prevVariance, indexes, previousDepth) {
startingPoint = (startingPoint || 0) + 1;
prevVariance = prevVariance || 0;
indexes = indexes || (new Array(amount));
previousDepth = previousDepth || 0;
var depth = previousDepth + 1; // t
var variance;
for (var i = startingPoint; i < levelMax - amount + previousDepth; i++) {
variance = prevVariance + H[index(startingPoint, i)];
indexes[depth - 1] = i;
if (depth + 1 < amount + 1) {
// we need to go deeper
iterateRecursive(i, variance, indexes, depth);
} else {
// enough, we can compare values now
variance += H[index(i + 1, levelMax)];
if (maxSig < variance) {
maxSig = variance;
colorStops = indexes.slice();
}
}
}
}
iterateRecursive(levelMin || 0);
return colorStops ? colorStops : [];
},
/**
* Automatically finds threshold value using Algorithm For Multilevel Thresholding
*
* @param {number} [levelMin]
* @param {number} [levelMax]
* @returns {null|number}
*/
autoThreshold: function(levelMin, levelMax) {
var value = this.multilevelThresholding(1, levelMin, levelMax);
return value.length ? value[0] : null;
},
/**
* Returns dominant color in given range. Returns -1 if not a single color from the range present on the image
*
* @param [levelMin=0]
* @param [levelMax=255]
* @param [tolerance=1]
* @returns {number}
*/
getDominantColor: function(levelMin, levelMax, tolerance) {
levelMin = normalizeMinMax(levelMin, levelMax);
levelMax = levelMin[1];
levelMin = levelMin[0];
tolerance = tolerance || 1;
var colors = this.data,
dominantIndex = -1,
dominantValue = -1,
i, j, tmp;
if (levelMin === levelMax) {
return colors[levelMin] ? levelMin : -1;
}
for (i=levelMin; i <= levelMax; i++) {
tmp = 0;
for (j = ~~(tolerance / -2); j < tolerance; j++) {
tmp += utils.between(i + j, 0, COLOR_RANGE_END) ? colors[i + j] : 0;
}
var summIsBigger = tmp > dominantValue;
var summEqualButMainColorIsBigger = dominantValue === tmp && (dominantIndex < 0 || colors[i] > colors[dominantIndex]);
if (summIsBigger || summEqualButMainColorIsBigger) {
dominantIndex = i;
dominantValue = tmp;
}
}
return dominantValue <= 0 ? -1 : dominantIndex;
},
/**
* Returns stats for histogram or its segment.
*
* Returned object contains median, mean and standard deviation for pixel values;
* peak, mean and median number of pixels per level and few other values
*
* If no pixels colors from specified range present on the image - most values will be NaN
*
* @param {Number} [levelMin=0] - histogram segment start
* @param {Number} [levelMax=255] - histogram segment end
* @param {Boolean} [refresh=false] - if cached result can be returned
* @returns {{levels: {mean: (number|*), median: *, stdDev: number, unique: number}, pixelsPerLevel: {mean: (number|*), median: (number|*), peak: number}, pixels: number}}
*/
getStats: function(levelMin, levelMax, refresh) {
levelMin = normalizeMinMax(levelMin, levelMax);
levelMax = levelMin[1];
levelMin = levelMin[0];
if (!refresh && this._cachedStats[levelMin + '-' + levelMax]) {
return this._cachedStats[levelMin + '-' + levelMax];
}
var data = this.data;
var sortedIndexes = this._getSortedIndexes();
var pixelsTotal = 0;
var medianValue = null;
var meanValue;
var medianPixelIndex;
var pixelsPerLevelMean;
var pixelsPerLevelMedian;
var tmpSumOfDeviations = 0;
var tmpPixelsIterated = 0;
var allPixelValuesCombined = 0;
var i, tmpPixels, tmpPixelValue;
var uniqueValues = 0; // counter for levels that's represented by at least one pixel
var mostPixelsPerLevel = 0;
// Finding number of pixels and mean
for (i = levelMin; i <= levelMax; i++) {
pixelsTotal += data[i];
allPixelValuesCombined += data[i] * i;
uniqueValues += data[i] === 0 ? 0 : 1;
if (mostPixelsPerLevel < data[i]) {
mostPixelsPerLevel = data[i];
}
}
meanValue = allPixelValuesCombined / pixelsTotal;
pixelsPerLevelMean = pixelsTotal / (levelMax - levelMin);
pixelsPerLevelMedian = pixelsTotal / uniqueValues;
medianPixelIndex = Math.floor(pixelsTotal / 2);
// Finding median and standard deviation
for (i = 0; i < COLOR_DEPTH; i++) {
tmpPixelValue = sortedIndexes[i];
tmpPixels = data[tmpPixelValue];
if (tmpPixelValue < levelMin || tmpPixelValue > levelMax) {
continue;
}
tmpPixelsIterated += tmpPixels;
tmpSumOfDeviations += Math.pow(tmpPixelValue - meanValue, 2) * tmpPixels;
if (medianValue === null && tmpPixelsIterated >= medianPixelIndex) {
medianValue = tmpPixelValue;
}
}
return this._cachedStats[levelMin + '-' + levelMax] = {
// various pixel counts for levels (0..255)
levels: {
mean: meanValue,
median: medianValue,
stdDev: Math.sqrt(tmpSumOfDeviations / pixelsTotal),
unique: uniqueValues
},
// what's visually represented as bars
pixelsPerLevel: {
mean: pixelsPerLevelMean,
median: pixelsPerLevelMedian,
peak: mostPixelsPerLevel
},
pixels: pixelsTotal
};
}
};
module.exports = Histogram;
+13
View File
@@ -0,0 +1,13 @@
'use strict';
var Point = require('./Point');
function Opti() {
this.pen = 0;
this.c = [new Point(), new Point()];
this.t = 0;
this.s = 0;
this.alpha = 0;
}
module.exports = Opti;
+14
View File
@@ -0,0 +1,14 @@
'use strict';
function Path() {
this.area = 0;
this.len = 0;
this.curve = {};
this.pt = [];
this.minX = 100000;
this.minY = 100000;
this.maxX = -1;
this.maxY = -1;
}
module.exports = Path;
+14
View File
@@ -0,0 +1,14 @@
'use strict';
function Point(x, y) {
this.x = x || 0;
this.y = y || 0;
}
Point.prototype = {
copy: function() {
return new Point(this.x, this.y);
}
};
module.exports = Point;
+11
View File
@@ -0,0 +1,11 @@
'use strict';
function Quad() {
this.data = [0,0,0,0,0,0,0,0,0];
}
Quad.prototype.at = function(x, y) {
return this.data[x * 3 + y];
};
module.exports = Quad;
+11
View File
@@ -0,0 +1,11 @@
'use strict';
function Sum(x, y, xy, x2, y2) {
this.x = x;
this.y = y;
this.xy = xy;
this.x2 = x2;
this.y2 = y2;
}
module.exports = Sum;
+253
View File
@@ -0,0 +1,253 @@
'use strict';
var Point = require('./types/Point');
var attrRegexps = {};
function getAttrRegexp(attrName) {
if (attrRegexps[attrName]) {
return attrRegexps[attrName];
}
attrRegexps[attrName] = new RegExp(' ' + attrName + '="((?:\\\\(?=")"|[^"])+)"', 'i');
return attrRegexps[attrName];
}
function setHtmlAttribute(html, attrName, value) {
var attr = ' ' + attrName + '="' + value + '"';
if (html.indexOf(' ' + attrName + '="') === -1) {
html = html.replace(/<[a-z]+/i, function(beginning) { return beginning + attr; });
} else {
html = html.replace(getAttrRegexp(attrName), attr);
}
return html;
}
function fixed(number) {
return number.toFixed(3).replace('.000', '');
}
function mod(a, n) {
return a >= n ? a % n : a>=0 ? a : n-1-(-1-a) % n;
}
function xprod(p1, p2) {
return p1.x * p2.y - p1.y * p2.x;
}
function cyclic(a, b, c) {
if (a <= c) {
return (a <= b && b < c);
} else {
return (a <= b || b < c);
}
}
function sign(i) {
return i > 0 ? 1 : i < 0 ? -1 : 0;
}
function quadform(Q, w) {
var v = new Array(3), i, j, sum;
v[0] = w.x;
v[1] = w.y;
v[2] = 1;
sum = 0.0;
for (i=0; i<3; i++) {
for (j=0; j<3; j++) {
sum += v[i] * Q.at(i, j) * v[j];
}
}
return sum;
}
function interval(lambda, a, b) {
var res = new Point();
res.x = a.x + lambda * (b.x - a.x);
res.y = a.y + lambda * (b.y - a.y);
return res;
}
function dorth_infty(p0, p2) {
var r = new Point();
r.y = sign(p2.x - p0.x);
r.x = -sign(p2.y - p0.y);
return r;
}
function ddenom(p0, p2) {
var r = dorth_infty(p0, p2);
return r.y * (p2.x - p0.x) - r.x * (p2.y - p0.y);
}
function dpara(p0, p1, p2) {
var x1, y1, x2, y2;
x1 = p1.x - p0.x;
y1 = p1.y - p0.y;
x2 = p2.x - p0.x;
y2 = p2.y - p0.y;
return x1 * y2 - x2 * y1;
}
function cprod(p0, p1, p2, p3) {
var x1, y1, x2, y2;
x1 = p1.x - p0.x;
y1 = p1.y - p0.y;
x2 = p3.x - p2.x;
y2 = p3.y - p2.y;
return x1 * y2 - x2 * y1;
}
function iprod(p0, p1, p2) {
var x1, y1, x2, y2;
x1 = p1.x - p0.x;
y1 = p1.y - p0.y;
x2 = p2.x - p0.x;
y2 = p2.y - p0.y;
return x1*x2 + y1*y2;
}
function iprod1(p0, p1, p2, p3) {
var x1, y1, x2, y2;
x1 = p1.x - p0.x;
y1 = p1.y - p0.y;
x2 = p3.x - p2.x;
y2 = p3.y - p2.y;
return x1 * x2 + y1 * y2;
}
function ddist(p, q) {
return Math.sqrt((p.x - q.x) * (p.x - q.x) + (p.y - q.y) * (p.y - q.y));
}
module.exports = {
luminance: function (r, g, b) {
return Math.round(0.2126 * r + 0.7153 * g + 0.0721 * b);
},
between: function(val, min, max) {
return val >= min && val <= max;
},
clamp: function(val, min, max) {
return Math.min(max, Math.max(min, val));
},
isNumber: function(val) {
return typeof val === 'number';
},
setHtmlAttr: setHtmlAttribute,
/**
* Generates path instructions for given curve
*
* @param {Curve} curve
* @param {Number} [scale]
* @returns {string}
*/
renderCurve: function(curve, scale) {
scale = scale || { x: 1, y: 1 };
var startingPoint = curve.c[(curve.n - 1) * 3 + 2];
var path = [
'M '
+ fixed(startingPoint.x * scale.x) + ' '
+ fixed(startingPoint.y * scale.y)
];
curve.tag.forEach(function(tag, i) {
var i3 = i * 3;
var p0 = curve.c[i3];
var p1 = curve.c[i3 + 1];
var p2 = curve.c[i3 + 2];
if (tag === "CURVE") {
path.push(
'C '
+ fixed(p0.x * scale.x) + ' ' + fixed(p0.y * scale.y) + ', '
+ fixed(p1.x * scale.x) + ' ' + fixed(p1.y * scale.y) + ', '
+ fixed(p2.x * scale.x) + ' ' + fixed(p2.y * scale.y)
);
} else if (tag === "CORNER") {
path.push(
'L '
+ fixed(p1.x * scale.x) + ' ' + fixed(p1.y * scale.y) + ' '
+ fixed(p2.x * scale.x) + ' ' + fixed(p2.y * scale.y)
);
}
});
return path.join(' ');
},
bezier: function bezier(t, p0, p1, p2, p3) {
var s = 1 - t, res = new Point();
res.x = s*s*s*p0.x + 3*(s*s*t)*p1.x + 3*(t*t*s)*p2.x + t*t*t*p3.x;
res.y = s*s*s*p0.y + 3*(s*s*t)*p1.y + 3*(t*t*s)*p2.y + t*t*t*p3.y;
return res;
},
tangent: function tangent(p0, p1, p2, p3, q0, q1) {
var A, B, C, a, b, c, d, s, r1, r2;
A = cprod(p0, p1, q0, q1);
B = cprod(p1, p2, q0, q1);
C = cprod(p2, p3, q0, q1);
a = A - 2 * B + C;
b = -2 * A + 2 * B;
c = A;
d = b * b - 4 * a * c;
if (a===0 || d<0) {
return -1.0;
}
s = Math.sqrt(d);
r1 = (-b + s) / (2 * a);
r2 = (-b - s) / (2 * a);
if (r1 >= 0 && r1 <= 1) {
return r1;
} else if (r2 >= 0 && r2 <= 1) {
return r2;
} else {
return -1.0;
}
},
mod: mod,
xprod: xprod,
cyclic: cyclic,
sign: sign,
quadform: quadform,
interval: interval,
dorth_infty: dorth_infty,
ddenom: ddenom,
dpara: dpara,
cprod: cprod,
iprod: iprod,
iprod1: iprod1,
ddist: ddist
};
-452
View File
@@ -1,452 +0,0 @@
let wasm;
function isLikeNone(x) {
return x === undefined || x === null;
}
let cachedDataViewMemory0 = null;
function getDataViewMemory0() {
if (cachedDataViewMemory0 === null || cachedDataViewMemory0.buffer.detached === true || (cachedDataViewMemory0.buffer.detached === undefined && cachedDataViewMemory0.buffer !== wasm.memory.buffer)) {
cachedDataViewMemory0 = new DataView(wasm.memory.buffer);
}
return cachedDataViewMemory0;
}
function debugString(val) {
// primitive types
const type = typeof val;
if (type == 'number' || type == 'boolean' || val == null) {
return `${val}`;
}
if (type == 'string') {
return `"${val}"`;
}
if (type == 'symbol') {
const description = val.description;
if (description == null) {
return 'Symbol';
} else {
return `Symbol(${description})`;
}
}
if (type == 'function') {
const name = val.name;
if (typeof name == 'string' && name.length > 0) {
return `Function(${name})`;
} else {
return 'Function';
}
}
// objects
if (Array.isArray(val)) {
const length = val.length;
let debug = '[';
if (length > 0) {
debug += debugString(val[0]);
}
for(let i = 1; i < length; i++) {
debug += ', ' + debugString(val[i]);
}
debug += ']';
return debug;
}
// Test for built-in
const builtInMatches = /\[object ([^\]]+)\]/.exec(toString.call(val));
let className;
if (builtInMatches && builtInMatches.length > 1) {
className = builtInMatches[1];
} else {
// Failed to match the standard '[object ClassName]'
return toString.call(val);
}
if (className == 'Object') {
// we're a user defined class or Object
// JSON.stringify avoids problems with cycles, and is generally much
// easier than looping through ownProperties of `val`.
try {
return 'Object(' + JSON.stringify(val) + ')';
} catch (_) {
return 'Object';
}
}
// errors
if (val instanceof Error) {
return `${val.name}: ${val.message}\n${val.stack}`;
}
// TODO we could test for more things here, like `Set`s and `Map`s.
return className;
}
let WASM_VECTOR_LEN = 0;
let cachedUint8ArrayMemory0 = null;
function getUint8ArrayMemory0() {
if (cachedUint8ArrayMemory0 === null || cachedUint8ArrayMemory0.byteLength === 0) {
cachedUint8ArrayMemory0 = new Uint8Array(wasm.memory.buffer);
}
return cachedUint8ArrayMemory0;
}
const cachedTextEncoder = (typeof TextEncoder !== 'undefined' ? new TextEncoder('utf-8') : { encode: () => { throw Error('TextEncoder not available') } } );
const encodeString = (typeof cachedTextEncoder.encodeInto === 'function'
? function (arg, view) {
return cachedTextEncoder.encodeInto(arg, view);
}
: function (arg, view) {
const buf = cachedTextEncoder.encode(arg);
view.set(buf);
return {
read: arg.length,
written: buf.length
};
});
function passStringToWasm0(arg, malloc, realloc) {
if (realloc === undefined) {
const buf = cachedTextEncoder.encode(arg);
const ptr = malloc(buf.length, 1) >>> 0;
getUint8ArrayMemory0().subarray(ptr, ptr + buf.length).set(buf);
WASM_VECTOR_LEN = buf.length;
return ptr;
}
let len = arg.length;
let ptr = malloc(len, 1) >>> 0;
const mem = getUint8ArrayMemory0();
let offset = 0;
for (; offset < len; offset++) {
const code = arg.charCodeAt(offset);
if (code > 0x7F) break;
mem[ptr + offset] = code;
}
if (offset !== len) {
if (offset !== 0) {
arg = arg.slice(offset);
}
ptr = realloc(ptr, len, len = offset + arg.length * 3, 1) >>> 0;
const view = getUint8ArrayMemory0().subarray(ptr + offset, ptr + len);
const ret = encodeString(arg, view);
offset += ret.written;
ptr = realloc(ptr, len, offset, 1) >>> 0;
}
WASM_VECTOR_LEN = offset;
return ptr;
}
const cachedTextDecoder = (typeof TextDecoder !== 'undefined' ? new TextDecoder('utf-8', { ignoreBOM: true, fatal: true }) : { decode: () => { throw Error('TextDecoder not available') } } );
if (typeof TextDecoder !== 'undefined') { cachedTextDecoder.decode(); };
function getStringFromWasm0(ptr, len) {
ptr = ptr >>> 0;
return cachedTextDecoder.decode(getUint8ArrayMemory0().subarray(ptr, ptr + len));
}
function passArray8ToWasm0(arg, malloc) {
const ptr = malloc(arg.length * 1, 1) >>> 0;
getUint8ArrayMemory0().set(arg, ptr / 1);
WASM_VECTOR_LEN = arg.length;
return ptr;
}
/**
* @param {Uint8Array} pixels
* @param {number} width
* @param {number} height
* @param {any} config_js
* @returns {string}
*/
export function to_svg(pixels, width, height, config_js) {
let deferred2_0;
let deferred2_1;
try {
const ptr0 = passArray8ToWasm0(pixels, wasm.__wbindgen_malloc);
const len0 = WASM_VECTOR_LEN;
const ret = wasm.to_svg(ptr0, len0, width, height, config_js);
deferred2_0 = ret[0];
deferred2_1 = ret[1];
return getStringFromWasm0(ret[0], ret[1]);
} finally {
wasm.__wbindgen_free(deferred2_0, deferred2_1, 1);
}
}
async function __wbg_load(module, imports) {
if (typeof Response === 'function' && module instanceof Response) {
if (typeof WebAssembly.instantiateStreaming === 'function') {
try {
return await WebAssembly.instantiateStreaming(module, imports);
} catch (e) {
if (module.headers.get('Content-Type') != 'application/wasm') {
console.warn("`WebAssembly.instantiateStreaming` failed because your server does not serve Wasm with `application/wasm` MIME type. Falling back to `WebAssembly.instantiate` which is slower. Original error:\n", e);
} else {
throw e;
}
}
}
const bytes = await module.arrayBuffer();
return await WebAssembly.instantiate(bytes, imports);
} else {
const instance = await WebAssembly.instantiate(module, imports);
if (instance instanceof WebAssembly.Instance) {
return { instance, module };
} else {
return instance;
}
}
}
function __wbg_get_imports() {
const imports = {};
imports.wbg = {};
imports.wbg.__wbg_buffer_609cc3eee51ed158 = function(arg0) {
const ret = arg0.buffer;
return ret;
};
imports.wbg.__wbg_entries_3265d4158b33e5dc = function(arg0) {
const ret = Object.entries(arg0);
return ret;
};
imports.wbg.__wbg_error_524f506f44df1645 = function(arg0) {
console.error(arg0);
};
imports.wbg.__wbg_get_b9b93047fe3cf45b = function(arg0, arg1) {
const ret = arg0[arg1 >>> 0];
return ret;
};
imports.wbg.__wbg_getwithrefkey_1dc361bd10053bfe = function(arg0, arg1) {
const ret = arg0[arg1];
return ret;
};
imports.wbg.__wbg_instanceof_ArrayBuffer_e14585432e3737fc = function(arg0) {
let result;
try {
result = arg0 instanceof ArrayBuffer;
} catch (_) {
result = false;
}
const ret = result;
return ret;
};
imports.wbg.__wbg_instanceof_Uint8Array_17156bcf118086a9 = function(arg0) {
let result;
try {
result = arg0 instanceof Uint8Array;
} catch (_) {
result = false;
}
const ret = result;
return ret;
};
imports.wbg.__wbg_isSafeInteger_343e2beeeece1bb0 = function(arg0) {
const ret = Number.isSafeInteger(arg0);
return ret;
};
imports.wbg.__wbg_length_a446193dc22c12f8 = function(arg0) {
const ret = arg0.length;
return ret;
};
imports.wbg.__wbg_length_e2d2a49132c1b256 = function(arg0) {
const ret = arg0.length;
return ret;
};
imports.wbg.__wbg_new_a12002a7f91c75be = function(arg0) {
const ret = new Uint8Array(arg0);
return ret;
};
imports.wbg.__wbg_set_65595bdd868b3009 = function(arg0, arg1, arg2) {
arg0.set(arg1, arg2 >>> 0);
};
imports.wbg.__wbindgen_as_number = function(arg0) {
const ret = +arg0;
return ret;
};
imports.wbg.__wbindgen_bigint_from_u64 = function(arg0) {
const ret = BigInt.asUintN(64, arg0);
return ret;
};
imports.wbg.__wbindgen_bigint_get_as_i64 = function(arg0, arg1) {
const v = arg1;
const ret = typeof(v) === 'bigint' ? v : undefined;
getDataViewMemory0().setBigInt64(arg0 + 8 * 1, isLikeNone(ret) ? BigInt(0) : ret, true);
getDataViewMemory0().setInt32(arg0 + 4 * 0, !isLikeNone(ret), true);
};
imports.wbg.__wbindgen_boolean_get = function(arg0) {
const v = arg0;
const ret = typeof(v) === 'boolean' ? (v ? 1 : 0) : 2;
return ret;
};
imports.wbg.__wbindgen_debug_string = function(arg0, arg1) {
const ret = debugString(arg1);
const ptr1 = passStringToWasm0(ret, wasm.__wbindgen_malloc, wasm.__wbindgen_realloc);
const len1 = WASM_VECTOR_LEN;
getDataViewMemory0().setInt32(arg0 + 4 * 1, len1, true);
getDataViewMemory0().setInt32(arg0 + 4 * 0, ptr1, true);
};
imports.wbg.__wbindgen_error_new = function(arg0, arg1) {
const ret = new Error(getStringFromWasm0(arg0, arg1));
return ret;
};
imports.wbg.__wbindgen_in = function(arg0, arg1) {
const ret = arg0 in arg1;
return ret;
};
imports.wbg.__wbindgen_init_externref_table = function() {
const table = wasm.__wbindgen_export_2;
const offset = table.grow(4);
table.set(0, undefined);
table.set(offset + 0, undefined);
table.set(offset + 1, null);
table.set(offset + 2, true);
table.set(offset + 3, false);
;
};
imports.wbg.__wbindgen_is_bigint = function(arg0) {
const ret = typeof(arg0) === 'bigint';
return ret;
};
imports.wbg.__wbindgen_is_object = function(arg0) {
const val = arg0;
const ret = typeof(val) === 'object' && val !== null;
return ret;
};
imports.wbg.__wbindgen_is_string = function(arg0) {
const ret = typeof(arg0) === 'string';
return ret;
};
imports.wbg.__wbindgen_is_undefined = function(arg0) {
const ret = arg0 === undefined;
return ret;
};
imports.wbg.__wbindgen_jsval_eq = function(arg0, arg1) {
const ret = arg0 === arg1;
return ret;
};
imports.wbg.__wbindgen_jsval_loose_eq = function(arg0, arg1) {
const ret = arg0 == arg1;
return ret;
};
imports.wbg.__wbindgen_memory = function() {
const ret = wasm.memory;
return ret;
};
imports.wbg.__wbindgen_number_get = function(arg0, arg1) {
const obj = arg1;
const ret = typeof(obj) === 'number' ? obj : undefined;
getDataViewMemory0().setFloat64(arg0 + 8 * 1, isLikeNone(ret) ? 0 : ret, true);
getDataViewMemory0().setInt32(arg0 + 4 * 0, !isLikeNone(ret), true);
};
imports.wbg.__wbindgen_string_get = function(arg0, arg1) {
const obj = arg1;
const ret = typeof(obj) === 'string' ? obj : undefined;
var ptr1 = isLikeNone(ret) ? 0 : passStringToWasm0(ret, wasm.__wbindgen_malloc, wasm.__wbindgen_realloc);
var len1 = WASM_VECTOR_LEN;
getDataViewMemory0().setInt32(arg0 + 4 * 1, len1, true);
getDataViewMemory0().setInt32(arg0 + 4 * 0, ptr1, true);
};
imports.wbg.__wbindgen_string_new = function(arg0, arg1) {
const ret = getStringFromWasm0(arg0, arg1);
return ret;
};
imports.wbg.__wbindgen_throw = function(arg0, arg1) {
throw new Error(getStringFromWasm0(arg0, arg1));
};
return imports;
}
function __wbg_init_memory(imports, memory) {
}
function __wbg_finalize_init(instance, module) {
wasm = instance.exports;
__wbg_init.__wbindgen_wasm_module = module;
cachedDataViewMemory0 = null;
cachedUint8ArrayMemory0 = null;
wasm.__wbindgen_start();
return wasm;
}
function initSync(module) {
if (wasm !== undefined) return wasm;
if (typeof module !== 'undefined') {
if (Object.getPrototypeOf(module) === Object.prototype) {
({module} = module)
} else {
console.warn('using deprecated parameters for `initSync()`; pass a single object instead')
}
}
const imports = __wbg_get_imports();
__wbg_init_memory(imports);
if (!(module instanceof WebAssembly.Module)) {
module = new WebAssembly.Module(module);
}
const instance = new WebAssembly.Instance(module, imports);
return __wbg_finalize_init(instance, module);
}
async function __wbg_init(module_or_path) {
if (wasm !== undefined) return wasm;
if (typeof module_or_path !== 'undefined') {
if (Object.getPrototypeOf(module_or_path) === Object.prototype) {
({module_or_path} = module_or_path)
} else {
console.warn('using deprecated parameters for the initialization function; pass a single object instead')
}
}
if (typeof module_or_path === 'undefined') {
// 本地改动:上游这里用 new URL('vtracer_bg.wasm', import.meta.url) 默认取同目录 wasm。
// 本插件把 wasm 以 base64 内联(宿主发布链路只接受单个 .js),且产物是 IIFE(无 import.meta),
// 永远由调用方显式传字节,因此这里直接报错而不是留一条会崩的默认路径。
throw new Error('vtracer: 必须显式传入 wasm 字节(本插件内联分发,不支持默认路径加载)')
}
const imports = __wbg_get_imports();
if (typeof module_or_path === 'string' || (typeof Request === 'function' && module_or_path instanceof Request) || (typeof URL === 'function' && module_or_path instanceof URL)) {
module_or_path = fetch(module_or_path);
}
__wbg_init_memory(imports);
const { instance, module } = await __wbg_load(await module_or_path, imports);
return __wbg_finalize_init(instance, module);
}
export { initSync };
export default __wbg_init;
// 本地改动:visioncortex 在部分极端参数下会 abort(wasm 报 unreachable),
// 此时实例已损坏、后续调用全部失败;而 __wbg_init 见到 wasm 已存在会直接返回旧实例。
// 因此提供一个显式复位钩子,让上层的「出错了就重建实例重试一次」成为可能。
export function __reset_wasm() {
wasm = undefined;
}
Binary file not shown.
-4
View File
@@ -1,4 +0,0 @@
// 自动生成,勿手改:由 tools/build-wasm-b64.mjs 从 plugin/vendor/vtracer.wasm 生成。
// 宿主发布链路(plugins-publish.mjs)只接受单个 .js,wasm 无法作为独立文件分发,故以 base64 内联;
// 运行时 atob 解码成 Uint8Array 后交给 WebAssembly.instantiate。体积代价约 +33%。
export default "AGFzbQEAAAAB/gI4YAN/f38Bf2ACf38Bf2ACf38AYAN/f38AYAF/AGAFf39/f38AYAR/f39/AGAEf39/fwF/YAF/AX9gBX9/f39/AX9gAW8Bf2AGf39/f39/AGAHf39/f39/fwBgAn9vAGAAAGADf39/AX5gAm9vAX9gAW8Bb2ACf38Bb2AGf39/f39/AX9gBH98f38AYAN/f34Bf2AEf39/fgBgAAJ/f2ABfgFvYAFvAGACb28Bb2ACb38Bb2AAAW9gA29vfwBgAW8BfGAJf39/f398fH98AGABfAF8YAABf2AJf39/f39/fn5+AGAHf39/f39/fwF/YAN+f38Bf2ADf398AGAFf3x8f38AYAN+fn8BfmACf34AYAJ/fwF8YAR/f3x8AGAEf3x8fwBgBHx8fHwBfGADf3x/AGAFf39/f28Cf39gBH9/fn8AYAN/fHwAYAd/fHx8fHx8AGAFf399f38AYAR/fX9/AGAFf398f38AYAV/f35/fwBgBH9+f38AYAJ8fgF8AvAHHwN3YmcVX193YmluZGdlbl9zdHJpbmdfZ2V0AA0Dd2JnFF9fd2JpbmRnZW5faXNfc3RyaW5nAAoDd2JnFF9fd2JpbmRnZW5faXNfYmlnaW50AAoDd2JnHF9fd2JpbmRnZW5fYmlnaW50X2dldF9hc19pNjQADQN3YmcaX193YmluZGdlbl9iaWdpbnRfZnJvbV91NjQAGAN3YmcTX193YmluZGdlbl9qc3ZhbF9lcQAQA3diZxRfX3diaW5kZ2VuX2Vycm9yX25ldwASA3diZxVfX3diaW5kZ2VuX251bWJlcl9nZXQADQN3YmcVX193YmluZGdlbl9zdHJpbmdfbmV3ABIDd2JnHF9fd2JnX2Vycm9yXzUyNGY1MDZmNDRkZjE2NDUAGQN3YmcUX193YmluZGdlbl9pc19vYmplY3QACgN3YmckX193YmdfZ2V0d2l0aHJlZmtleV8xZGMzNjFiZDEwMDUzYmZlABoDd2JnF19fd2JpbmRnZW5faXNfdW5kZWZpbmVkAAoDd2JnDV9fd2JpbmRnZW5faW4AEAN3YmcdX193YmdfbGVuZ3RoX2UyZDJhNDkxMzJjMWIyNTYACgN3YmcaX193YmdfZ2V0X2I5YjkzMDQ3ZmUzY2Y0NWIAGwN3YmcWX193YmluZGdlbl9ib29sZWFuX2dldAAKA3diZx1fX3diZ19sZW5ndGhfYTQ0NjE5M2RjMjJjMTJmOAAKA3diZxFfX3diaW5kZ2VuX21lbW9yeQAcA3diZx1fX3diZ19idWZmZXJfNjA5Y2MzZWVlNTFlZDE1OAARA3diZxpfX3diZ19uZXdfYTEyMDAyYTdmOTFjNzViZQARA3diZxpfX3diZ19zZXRfNjU1OTViZGQ4NjhiMzAwOQAdA3diZxlfX3diaW5kZ2VuX2pzdmFsX2xvb3NlX2VxABADd2JnLF9fd2JnX2luc3RhbmNlb2ZfVWludDhBcnJheV8xNzE1NmJjZjExODA4NmE5AAoDd2JnLV9fd2JnX2luc3RhbmNlb2ZfQXJyYXlCdWZmZXJfZTE0NTg1NDMyZTM3MzdmYwAKA3diZx5fX3diZ19lbnRyaWVzXzMyNjVkNDE1OGIzM2U1ZGMAEQN3YmckX193YmdfaXNTYWZlSW50ZWdlcl8zNDNlMmJlZWVlY2UxYmIwAAoDd2JnFF9fd2JpbmRnZW5fYXNfbnVtYmVyAB4Dd2JnEF9fd2JpbmRnZW5fdGhyb3cAAgN3YmcXX193YmluZGdlbl9kZWJ1Z19zdHJpbmcADQN3YmcfX193YmluZGdlbl9pbml0X2V4dGVybnJlZl90YWJsZQAOA4YDhAMIHwgDBQwMDAwCAAsLAwILCwIDBgwBBwIBAwAgBBMIAAABAQYAAAECFAAhIgEDCQIGCQECACMDAyQBCwABAwICAgMDBQECAQECAwIBCw4DAgEGAQYFAQMDAwICAgQFBgICAwsCAgIHBwACBQICAyUCBgMHBwIBAQEGJgEGBQ8CAAMFAicCBgcCFQgLAgUEAAIDAwIDFQAGACgCAwMCAQEDAgMIBAIAAgIpBQgDAgICAwICAgMWFgQDAQIEAgUAAAIDBioDAQACBCsGAgMBAQgJLAEEAwMtAwQEBA4EDgMFBQMABwECAgMAAC4CAi8PDwMCAjAIAQEFAgQCAAUCAgIEBwcBEwEHBwcFBQUFBzEHMgU0CTUDAwMDAwEGBAcCAAEEAQIDAQQEBAEEAQMACDcCBAEBCAEBAQEBAQEBAQEBAQABBAEFAgMBAgIBAQICAgkBAQADAwMEAQAEAAMBAggBAQICAgICAQEBAgECCQACAgQBBAgCAAQICAgIBAkGBgIGAgcABAkCcAFmZm8AgAEFAwEAEQYJAX8BQYCAwAALB3sHBm1lbW9yeQIABnRvX3N2ZwCIAhFfX3diaW5kZ2VuX21hbGxvYwDwARJfX3diaW5kZ2VuX3JlYWxsb2MAgQITX193YmluZGdlbl9leHBvcnRfMgEBD19fd2JpbmRnZW5fZnJlZQDlAhBfX3diaW5kZ2VuX3N0YXJ0AB4JvgEBAEEBC2XmAuIC6QLsAeICN4ICcZAD/gI06wH/AvACmQG4AvYCoQJ0ZekCUYcDlQGTAm/dAuoCQZQBogKxAqkBrwKxAr0CuQKvAq8CrgKwArICjAKNAtYC2gLZAtsC1wLUAtgC1QLTApoD8QJj+wLcApEDascCxgLcAViFA9wCZj/XAYYDU5QC3gLgAt0BW4kD7QLrAscC6QHsAogDugKWAWd+kwOjAs8BwQKHAocBlAOUA5QD7gJNiwOLA88CCriUB4QDjEACMH8EfiMAQdACayICJAACQAJAAkACQCAABEBBASEXAkAgACgCcEEBaw4CAAIFCyAAKAJ0IgEgAEEgaiIKKAIAIgMgASADSxshFCABIAEgACgCYCIVaiIDIAEgA0sbIRcgACgCZCIJIAlBCHYiEXIgCUEQdiISckH/AXFBAEcgCUH///8HS3IhEyAAQQxqIRAgAkH0AGohDiAALQB8IQ0gAC0AfUEBcSEZIABBFGohByAAQRxqIQgDQCABIBdHIAEgFEdxBEACQAJ/AkAgACgCaCIEBEAgAkFAayAAIAEgASAEbiILIARsayIDIAsQjwEgAkHFAGogACADIAtBAWsiDBCPASACQcoAaiAAIANBAWsiDyALEI8BIAJBzwBqIAAgDyAMEI8BAn8gASAESSIWBEBBACEEQQAhBUEAIgYgAw0BGgwFCyAIKAIAIAooAgAgACgCaCAMbCADakHs3sAAEKsCKAIAIQQgA0UNAiAECyEEIAgoAgAgCigCACAAKAJoIAtsIA9qQfzewAAQqwIoAgAhBSAWBH9BAAUgCCgCACAKKAIAIAAoAmggDGwgD2pBjN/AABCrAigCAAsMAgtB3N7AABD2AQALQQAhBUEACyEGAkAgBCAFRg0AAkAgAi0ASkEBcUUNACACLQBFQQFxRQ0AIAAoAjwgAigASyIMIAIoAEYiDyAAKAJAKAIUEQAARQ0AIA1BAXFFBEAgAi0AQEEBcUUNASAAKAI8IAIoAEEiFiAMIAAoAkAoAhQRAABFDQEgACgCPCAWIA8gACgCQCgCFBEAAEUNAQsgAEEQaiIMKAIAIAcoAgAgBRD3AigCCCAMKAIAIAcoAgAgBBD3AigCCE0EQCAAIAUgBBBMIAUgACgCeCIMQQFrRw0CIAwgBygCAEcNAiAAIAU2AngMAgsgACAEIAUQTCAFIQQMAgsMAQsgBCEFCwJAAkAgAi0AQEEBcQRAIAIgAigAQSIMNgKgAiATIAxB/wFxIAlB/wFxRnFFIAxBCHZB/wFxIBFB/wFxR3IgDEEQdkH/AXEgEkH/AXFHckUgCSAMc0GAgIAISXFFBEACQAJAAkACQCACLQBFQQFHDQAgACgCPCAMIAIoAEYgACgCQCgCFBEAAEUNACACLQBPQQFxRQ0AIAAoAjwgDCACKABQIAAoAkAoAhQRAAANAQsCQCACLQBKQQFHDQAgACgCPCAMIAIoAEsgACgCQCgCFBEAAEUNACACLQBPQQFxRQ0AIAAoAjwgDCACKABQIAAoAkAoAhQRAAANAgsgDUEBcQ0CDAULIAgoAgAgCigCACABQfzfwAAQqwIgBDYCACAAQRBqKAIAIAcoAgAgBBD5AiABIAJBoAJqIAMgCxCbAQwFCyAIKAIAIAooAgAgAUHs38AAEKsCIAU2AgAgAEEQaigCACAHKAIAIAUQ+QIgASACQaACaiADIAsQmwEMBAsgAi0AT0EBRw0CIAAoAjwgDCACKABQIAAoAkAoAhQRAABFDQIgCCgCACAKKAIAIAFB3N/AABCrAiAGNgIAIABBEGooAgAgBygCACAGEPkCIAEgAkGgAmogAyALEJsBDAMLIBkNAiAAQRBqKAIAIAcoAgBBABD5AiABIAJBoAJqIAMgCxCbAQwCC0Gc38AAEPUCAAsgAkEANgJUIA5BAEE4EEgaIAJBADYCrAEgAkEANgJwIAJCADcCaCACQoCAgIDAADcCYCACQgQ3AlggAkHUAGogASACQaACaiADIAsQmwECQCAAKAJ4IgQgBygCACIDTwRAIBAoAgAgA0YEQCMAQRBrIgQkACAEQQhqIBAgECgCAEEBQQRB3AAQayAEKAIIIgZBgYCAgHhHBEAgBCgCDBogBkGs38AAEOgCAAsgBEEQaiQACyAAQRBqKAIAIANB3ABsaiACQdQAakHcABA5GiAHIANBAWo2AgAMAQsgAEEQaigCACADIARBvN/AABClAiIDEMQCIAMgAkHUAGpB3AAQORoLIAAoAnghAyAIKAIAIAooAgAgAUHM38AAEKsCIAM2AgAgACAAKAJ4QQFqNgJ4CyABQQFqIQEMAQUgACAAKAJ0IBVqIgE2AnQgASAAQSBqKAIASQ0FIAB Line truncated