feat(image-vectorize): v0.2.1 精度可调 + 复制到剪贴板 + 高级默认展开
用户反馈三项: 1. 高级参数默认展开(不再藏起来),折叠按钮保留、展开状态记忆在 ctx.settings 2. 新增「复制 SVG」:一次写入 image/svg+xml + text/html + text/plain 三种口味, 粘到 Figma / Illustrator 直接是真矢量。Chrome 对可写 MIME 有白名单, 塞了不支持的类型会整次 write 失败,所以先 ClipboardItem.supports() 探测再逐级降级 3. 边缘精度可调:optTolerance 默认 0.2 → 0.05(三档 精细/标准/轻量), 大图降采样上限 2000 → 3000px(实测单色 3200px 96ms、灰度 4 层 3000px 179ms) 预览底部的说明改为胶囊提示(原 #75758a 裸文字在浅灰棋盘上几乎看不见), 面板间距压紧,高级区展开后整列参数在 980px 高下不用滚。 验证:本地 harness 38 项、真站 e2e 17 项(含真实剪贴板读回校验)全绿。
This commit is contained in:
1 parent
c4e4b15375
commit
d151de74a1
10 files changed
+367
-49
No files matched your search
@@ -22,10 +22,12 @@ v0.2 换 potrace,并且按用户要求**只做单色 / 灰度**(不做彩色
|
||||
|
||||
- 三个预设:文字 / 线稿(单色)、菜单 / 图文(灰度 3 层)、抠图轮廓(单色 + 强去毛刺)
|
||||
- 描摹方式:**灰度分层**(层数 2–5)/ **纯单色**
|
||||
- 高频参数只有两个滑杆:**去小点**(turdSize)、**边缘**(硬朗 / 标准 / 圆润 → alphaMax)
|
||||
- 高级:阈值(自动 / 手动)、反相(黑底白字用负片)、单色填充色
|
||||
- 参数:**去小点**(turdSize)、**边缘**(硬朗 / 标准 / 圆润 → alphaMax)、
|
||||
**精度**(精细 / 标准 / 轻量 → optTolerance 0.05 / 0.15 / 0.4,默认精细)
|
||||
- 高级(**默认展开**):阈值(自动 / 手动)、反相(黑底白字用负片)、单色填充色
|
||||
- 预览:按住空格对比原图;面板显示路径数 / 层数 / 体积 / 耗时
|
||||
- 输出:**保存为节点**(PNG,按输出倍率 1–4× 用矢量重绘)· **下载 SVG**(真矢量)
|
||||
- 输出:**复制 SVG**(写 `image/svg+xml` + `text/html` + `text/plain` 三种剪贴板口味,
|
||||
Figma / Illustrator 粘进去就是真矢量)· **下载 SVG** · **保存为节点**(PNG,按输出倍率 1–4× 从矢量重绘)
|
||||
|
||||
## 灰度分层为什么自己算阈值
|
||||
|
||||
@@ -39,6 +41,15 @@ v0.2 换 potrace,并且按用户要求**只做单色 / 灰度**(不做彩色
|
||||
2. **切点必须严格递增**。背景是巨大尖峰,多个切点会算出同一个亮度值 —— 去重后层数变少,
|
||||
Posterizer 还会算出 0 透明度让整层消失。
|
||||
|
||||
## 复制到剪贴板为什么写三种口味
|
||||
|
||||
剪贴板不像文件,只有一个「格式」——它同时可以装多份不同 MIME 的数据,读的一方自己挑。
|
||||
Figma 认 `image/svg+xml`(或 `text/html` 里的 `<svg>`)当**矢量**,只认 `text/plain` 的软件
|
||||
(某些编辑器)则退化成一段 SVG 源码。所以一次写入三种口味,谁挑哪个都能用。
|
||||
|
||||
Chrome 对可写 MIME 有白名单,**塞了不支持的类型会让整次 `write()` 失败**(不是忽略那一种),
|
||||
所以先用 `ClipboardItem.supports()` 探测,失败再逐级降级到 `writeText()`。
|
||||
|
||||
## 许可
|
||||
|
||||
potrace 与其 JS 移植都是 **GPL-2.0**(见 `plugin/vendor/potrace/LICENSE`)。当前用途是**自己用、
|
||||
@@ -51,12 +62,12 @@ potrace 与其 JS 移植都是 **GPL-2.0**(见 `plugin/vendor/potrace/LICENSE`
|
||||
```bash
|
||||
npm run build -- image-vectorize # plugin/ → src/index.js(esbuild IIFE)
|
||||
npm run validate # 契约校验
|
||||
node image-vectorize/tools/harness.mjs # 本地端到端(合成宿主 + 真 Chromium,30 项)
|
||||
node image-vectorize/tools/harness.mjs # 本地端到端(合成宿主 + 真 Chromium,38 项)
|
||||
node image-vectorize/tools/e2e-site.mjs # 真站(KV / SRI / CSP / 真实画布桥)
|
||||
|
||||
# 拿真实素材调参数(不进 CI,最快看到效果):
|
||||
node image-vectorize/tools/trace-cli.mjs ~/Desktop/menu.png --mode gray --levels 3
|
||||
node image-vectorize/tools/trace-cli.mjs ~/Desktop/logo.png --mode mono --turd 8
|
||||
node image-vectorize/tools/trace-cli.mjs ~/Desktop/logo.png --mode mono --turd 8 --tol 0.05
|
||||
# → 产物 SVG + 一张「原图 / 结果」对比图(~-/tmp/vz-cli/)
|
||||
```
|
||||
|
||||
@@ -65,12 +76,13 @@ node image-vectorize/tools/trace-cli.mjs ~/Desktop/logo.png --mode mono --turd 8
|
||||
```bash
|
||||
cp image-vectorize/src/index.js /tmp/plugin-image-vectorize.js
|
||||
cd ../image-workbench-web && node scripts/plugins-publish.mjs /tmp/plugin-image-vectorize.js \
|
||||
--version image-vectorize=0.2.0 --upload
|
||||
--version image-vectorize=0.2.1 --upload
|
||||
```
|
||||
|
||||
## 已知限制
|
||||
|
||||
- **照片不适合**:potrace 只懂明暗,照片会被压成几块灰阶(这不是 bug,是算法定位)
|
||||
- 小字号(<24px)文字描摹后仍会变形;灰度模式可缓解(把浅色笔画留在单独一层)
|
||||
- 超过 2000px 的图自动降到 2000px 再描摹(纯 JS 单线程,避免卡主线程)
|
||||
- 超过 3000px 的图自动降到 3000px 再描摹(实测单色 3200px 96ms、灰度 4 层 3000px 179ms;
|
||||
3600px 起跳到 389ms,所以 3000 是「细节不掉、又不卡主线程」的交点)
|
||||
- 灰度模式的「灰」是 `fill-opacity` 叠出来的(不是多条不同色 path),所以 SVG 里只有一种 fill 色
|
||||
@@ -1,7 +1,7 @@
|
||||
{
|
||||
"name": "@iwb-plugin/image-vectorize",
|
||||
"private": true,
|
||||
"version": "0.2.0",
|
||||
"version": "0.2.1",
|
||||
"description": "位图转矢量:potrace(纯 JS)单色/灰度描摹,输出 SVG 与 PNG 节点;对文字、logo、线稿保形好,不需要 wasm",
|
||||
"ibwPlugin": {
|
||||
"id": "image-vectorize",
|
||||
|
||||
@@ -24,20 +24,31 @@ export const MODES = ['gray', 'mono']
|
||||
export const LEVELS_MIN = 2
|
||||
export const LEVELS_MAX = 5
|
||||
|
||||
/** 描摹上限边(超过就降采样):potrace 是纯 JS 单线程,2000px 以上会明显卡主线程 */
|
||||
export const MAX_TRACE_SIDE = 2000
|
||||
/**
|
||||
* 描摹上限边(超过就降采样)。potrace 是纯 JS 单线程,实测:
|
||||
* 单色 3200px 96ms、灰度 4 层 3000px 179ms(3600px 已跳到 389ms,内存压力明显)。
|
||||
* 所以取 3000 —— 菜单/详情页这类大图的细节不再被降采样吃掉,同时仍在该帧内完成。
|
||||
*/
|
||||
export const MAX_TRACE_SIDE = 3000
|
||||
|
||||
export const DEFAULTS = {
|
||||
mode: 'gray', // 'gray' 灰度分层 / 'mono' 纯单色
|
||||
levels: 3, // 灰度层数(2–5,仅 gray)
|
||||
threshold: -1, // -1 = 自动(两种模式都支持)
|
||||
turdSize: 3, // 去小点:面积小于它的碎片直接丢(毛刺/噪点克星)
|
||||
alphaMax: 1, // 拐角平滑:0 全折线、1 默认、1.334 最圆
|
||||
alphaMax: 1, // 拐角阈值:0 全折线、1 默认、1.334 最圆
|
||||
// 曲线拟合容差(越小越贴合原图像素边缘,路径数据也越大)。
|
||||
// 上游默认 0.2 是「视觉上够用」的省数据值;实测 0.2 在文字笔画与圆角处会
|
||||
// 吃掉约半个像素的弯折,所以这里默认降到 0.05(用户 2026-11-05 要求「边缘精度再高一点」)。
|
||||
optTolerance: 0.05,
|
||||
invert: false, // 反相:描摹亮部(黑底白字场景)
|
||||
color: '#1a1a1a', // mono 的填充色
|
||||
outScale: 1, // 输出尺寸倍率(只放大尺寸,不重算曲线)
|
||||
}
|
||||
|
||||
/** 曲线精度三档(UI 用):越大越省路径数据,越小越贴合像素 */
|
||||
export const TOLERANCE_TONES = { fine: 0.05, normal: 0.15, light: 0.4 }
|
||||
|
||||
const clampInt = (v, min, max, dflt) => {
|
||||
const n = Math.round(Number(v))
|
||||
return Number.isFinite(n) ? Math.min(max, Math.max(min, n)) : dflt
|
||||
@@ -55,6 +66,10 @@ export function normalizeParams(p) {
|
||||
const n = Number(src.alphaMax)
|
||||
return Number.isFinite(n) ? Math.min(1.334, Math.max(0, n)) : DEFAULTS.alphaMax
|
||||
})(),
|
||||
optTolerance: (() => {
|
||||
const n = Number(src.optTolerance)
|
||||
return Number.isFinite(n) ? Math.min(2, Math.max(0.01, n)) : DEFAULTS.optTolerance
|
||||
})(),
|
||||
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)),
|
||||
@@ -143,7 +158,7 @@ export function traceImageData(imageData, params) {
|
||||
turdSize: p.turdSize,
|
||||
alphaMax: p.alphaMax,
|
||||
optCurve: true,
|
||||
optTolerance: 0.2,
|
||||
optTolerance: p.optTolerance,
|
||||
blackOnWhite: !p.invert,
|
||||
color: p.color,
|
||||
})
|
||||
@@ -159,7 +174,7 @@ export function traceImageData(imageData, params) {
|
||||
turdSize: p.turdSize,
|
||||
alphaMax: p.alphaMax,
|
||||
optCurve: true,
|
||||
optTolerance: 0.2,
|
||||
optTolerance: p.optTolerance,
|
||||
blackOnWhite: !p.invert,
|
||||
fillStrategy: 'median', // 灰度:每层取该层亮度中位数
|
||||
color: '#000000', // 灰度靠 fill-opacity 叠出来,底色固定黑
|
||||
|
||||
@@ -19,8 +19,10 @@ var __IWB_VECTORIZE_MANIFEST__ = {
|
||||
threshold: { type: 'number', default: -1 },
|
||||
turdSize: { type: 'number', default: 3 },
|
||||
alphaMax: { type: 'number', default: 1 },
|
||||
optTolerance: { type: 'number', default: 0.05 },
|
||||
invert: { type: 'boolean', default: false },
|
||||
color: { type: 'string', default: '#1a1a1a' },
|
||||
outScale: { type: 'number', default: 2 }
|
||||
outScale: { type: 'number', default: 2 },
|
||||
advOpen: { type: 'boolean', default: true }
|
||||
},
|
||||
}
|
||||
@@ -132,12 +132,16 @@
|
||||
letter-spacing: 0.2px;
|
||||
}
|
||||
|
||||
/* 底部提示:浅灰棋盘上 #75758a 的裸文字几乎看不见(实测),改成深色胶囊 */
|
||||
.vz-hint {
|
||||
position: absolute;
|
||||
bottom: 14px;
|
||||
left: 50%;
|
||||
transform: translateX(-50%);
|
||||
color: #75758a;
|
||||
padding: 5px 11px;
|
||||
border-radius: 999px;
|
||||
background: rgba(22, 22, 30, 0.8);
|
||||
color: #dcdce8;
|
||||
font-size: 11px;
|
||||
pointer-events: none;
|
||||
white-space: nowrap;
|
||||
@@ -176,7 +180,7 @@
|
||||
.vz-panel {
|
||||
flex: 0 0 auto;
|
||||
width: 312px;
|
||||
padding: 14px 16px 18px;
|
||||
padding: 12px 15px 14px;
|
||||
background: #1e1e26;
|
||||
border-left: 1px solid #2e2e3a;
|
||||
overflow-y: auto;
|
||||
@@ -185,7 +189,7 @@
|
||||
.vz-panel::-webkit-scrollbar { width: 8px; }
|
||||
.vz-panel::-webkit-scrollbar-thumb { background: #3a3a48; border-radius: 4px; }
|
||||
|
||||
.vz-group + .vz-group { margin-top: 18px; padding-top: 16px; border-top: 1px solid #2b2b36; }
|
||||
.vz-group + .vz-group { margin-top: 14px; padding-top: 12px; border-top: 1px solid #2b2b36; }
|
||||
|
||||
.vz-group-title {
|
||||
font-size: 11px;
|
||||
@@ -206,7 +210,7 @@
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 2px;
|
||||
padding: 8px 9px;
|
||||
padding: 7px 9px;
|
||||
border: 1px solid #37374a;
|
||||
border-radius: 8px;
|
||||
background: #262631;
|
||||
@@ -229,7 +233,7 @@
|
||||
.vz-preset.active small { color: #79b79b; }
|
||||
|
||||
/* 分段控件 */
|
||||
.vz-row { margin-bottom: 11px; }
|
||||
.vz-row { margin-bottom: 9px; }
|
||||
/* 按模式隐藏的行(层数只在灰度、阈值只在手动)必须真的消失。
|
||||
踩过的坑:flex/块级元素上加 `hidden` 属性,如果 CSS 里另有 display 声明就会失效,
|
||||
于是「隐藏」只变成视觉上还在 —— 这里直接 !important 兜住所有形态。 */
|
||||
|
||||
@@ -12,11 +12,11 @@
|
||||
*/
|
||||
'use strict'
|
||||
|
||||
import { DEFAULTS, LEVELS_MIN, LEVELS_MAX, normalizeParams } from './engine.js'
|
||||
import { DEFAULTS, LEVELS_MIN, LEVELS_MAX, TOLERANCE_TONES, normalizeParams } from './engine.js'
|
||||
import { loadImage, prepareSource, svgToPngBlob, svgStats } from './trace.js'
|
||||
import { traceImageData } from './engine.js'
|
||||
|
||||
const SETTING_KEYS = ['preset', 'mode', 'levels', 'threshold', 'turdSize', 'alphaMax', 'invert', 'color', 'outScale']
|
||||
const SETTING_KEYS = ['preset', 'mode', 'levels', 'threshold', 'turdSize', 'alphaMax', 'optTolerance', 'invert', 'color', 'outScale', 'advOpen']
|
||||
|
||||
/** 三个预设:都围绕「自己出图」的实际场景,不放没用的组合 */
|
||||
const PRESETS = {
|
||||
@@ -52,7 +52,7 @@ function rangeHTML(name, label, min, max, step, value, hint) {
|
||||
'</div></div>'
|
||||
}
|
||||
|
||||
function panelHTML(params, preset, outScale) {
|
||||
function panelHTML(params, preset, outScale, advOpen) {
|
||||
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 + '">' +
|
||||
@@ -72,10 +72,14 @@ function panelHTML(params, preset, outScale) {
|
||||
|
||||
'<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">' +
|
||||
'<div class="vz-row"><div class="vz-row-label">边缘<span>拐角处理</span></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 class="vz-row"><div class="vz-row-label">精度<span>越高越贴合原图,曲线数据略多</span></div><div class="vz-seg" data-seg-group="precision">' +
|
||||
'<button type="button" data-seg="precision" data-value="fine">精细</button>' +
|
||||
'<button type="button" data-seg="precision" data-value="normal">标准</button>' +
|
||||
'<button type="button" data-seg="precision" data-value="light">轻量</button></div></div>' +
|
||||
'</div>' +
|
||||
|
||||
'<div class="vz-group">' +
|
||||
@@ -94,8 +98,8 @@ function panelHTML(params, preset, outScale) {
|
||||
'</div>' +
|
||||
|
||||
'<div class="vz-group">' +
|
||||
'<button type="button" class="vz-adv-toggle" data-act="adv" aria-expanded="false">高级参数<span data-adv-caret>▾</span></button>' +
|
||||
'<div class="vz-adv" data-adv hidden>' +
|
||||
'<button type="button" class="vz-adv-toggle" data-act="adv" aria-expanded="' + (advOpen ? 'true' : 'false') + '">高级参数<span data-adv-caret>' + (advOpen ? '▴' : '▾') + '</span></button>' +
|
||||
'<div class="vz-adv" data-adv' + (advOpen ? '' : ' hidden') + '>' +
|
||||
'<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>' +
|
||||
@@ -104,7 +108,6 @@ function panelHTML(params, preset, outScale) {
|
||||
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>'
|
||||
}
|
||||
@@ -117,6 +120,7 @@ function viewHTML(name) {
|
||||
'<span class="vz-title">位图转矢量<em data-meta>' + esc(name) + '</em></span>' +
|
||||
'<div class="vz-spacer"></div>' +
|
||||
'<button type="button" class="vz-btn" data-act="cancel">取消</button>' +
|
||||
'<button type="button" class="vz-btn" data-act="copy">复制 SVG</button>' +
|
||||
'<button type="button" class="vz-btn" data-act="svg">下载 SVG</button>' +
|
||||
'<button type="button" class="vz-btn vz-btn-primary" data-act="save">保存为节点</button>' +
|
||||
'</header>' +
|
||||
@@ -126,7 +130,7 @@ function viewHTML(name) {
|
||||
'<img class="vz-stage" data-stage="original" alt="原图" hidden>' +
|
||||
'<div class="vz-badge" data-badge>矢量预览</div>' +
|
||||
'<div class="vz-status" data-status hidden><i class="vz-dot"></i><span data-status-text></span></div>' +
|
||||
'<div class="vz-hint">按住空格键对比原图</div>' +
|
||||
'<div class="vz-hint">空格 对比原图 · 「复制 SVG」可直接粘到 Figma</div>' +
|
||||
'</div>' +
|
||||
'<aside class="vz-panel" data-panel></aside>' +
|
||||
'</div></div></div>'
|
||||
@@ -135,6 +139,8 @@ function viewHTML(name) {
|
||||
/** 边缘预设 → 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')
|
||||
/** 容差 → 精度档(0.05 精细 / 0.15 标准 / 0.4 轻量) */
|
||||
const tolToneOf = (tol) => (tol <= 0.08 ? 'fine' : tol >= 0.3 ? 'light' : 'normal')
|
||||
|
||||
export function createVectorizer(options) {
|
||||
const settings = options.settings
|
||||
@@ -148,6 +154,7 @@ export function createVectorizer(options) {
|
||||
let params = normalizeParams(DEFAULTS)
|
||||
let preset = 'text'
|
||||
let outScale = 2
|
||||
let advOpen = true
|
||||
let currentSvg = ''
|
||||
let currentBlobUrl = ''
|
||||
let seq = 0
|
||||
@@ -164,6 +171,7 @@ export function createVectorizer(options) {
|
||||
try { value = settings.get(key) } catch (e) { continue }
|
||||
if (value === undefined || value === null || value === '') continue
|
||||
if (key === 'invert') value = value === true || value === 'true' || value === 1 || value === '1'
|
||||
if (key === 'advOpen') value = !(value === false || value === 'false' || value === 0 || value === '0')
|
||||
out[key] = value
|
||||
}
|
||||
return out
|
||||
@@ -178,9 +186,11 @@ export function createVectorizer(options) {
|
||||
settings.set('threshold', params.threshold)
|
||||
settings.set('turdSize', params.turdSize)
|
||||
settings.set('alphaMax', params.alphaMax)
|
||||
settings.set('optTolerance', params.optTolerance)
|
||||
settings.set('invert', params.invert)
|
||||
settings.set('color', params.color)
|
||||
settings.set('outScale', outScale)
|
||||
settings.set('advOpen', advOpen)
|
||||
} catch (e) { /* 记忆失败不影响主流程 */ }
|
||||
}
|
||||
|
||||
@@ -236,6 +246,9 @@ export function createVectorizer(options) {
|
||||
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="precision"] button').forEach(function (btn) {
|
||||
btn.classList.toggle('active', btn.dataset.value === tolToneOf(params.optTolerance))
|
||||
})
|
||||
panel.querySelectorAll('[data-seg-group="invert"] button').forEach(function (btn) {
|
||||
btn.classList.toggle('active', (btn.dataset.value === '1') === params.invert)
|
||||
})
|
||||
@@ -314,6 +327,81 @@ export function createVectorizer(options) {
|
||||
debounceTimer = window.setTimeout(function () { writeSettings(); retrace() }, 120)
|
||||
}
|
||||
|
||||
// ---------- 复制到剪贴板 ----------
|
||||
|
||||
/**
|
||||
* 把 SVG 放进剪贴板,尽量让设计软件(Figma / Illustrator / Sketch)认成**矢量**而不是文本。
|
||||
*
|
||||
* 三种「口味」各有用途,缺一不可:
|
||||
* - `image/svg+xml`:真正的矢量 MIME,Illustrator / Inkscape 直接吃;
|
||||
* - `text/html` 里带 `<svg>`:Figma 走 HTML 解析分支时会认成矢量;
|
||||
* - `text/plain`:兜底(也有软件只读纯文本里的 SVG 源码)。
|
||||
* Chrome 对可写 MIME 有白名单,塞了不支持的类型会**整次 write 失败**,
|
||||
* 所以先用 `ClipboardItem.supports()` 探测,失败再逐级降级。
|
||||
*/
|
||||
async function writeSvgToClipboard(svgText) {
|
||||
const nav = typeof navigator === 'undefined' ? null : navigator
|
||||
const Item = typeof window === 'undefined' ? null : window.ClipboardItem
|
||||
const plain = new Blob([svgText], { type: 'text/plain' })
|
||||
const html = new Blob([svgText], { type: 'text/html' })
|
||||
let svgFlavor = false
|
||||
|
||||
if (nav && nav.clipboard && typeof nav.clipboard.write === 'function' && typeof Item === 'function') {
|
||||
try {
|
||||
svgFlavor = typeof Item.supports !== 'function' || Item.supports('image/svg+xml')
|
||||
} catch (e) {
|
||||
svgFlavor = false
|
||||
}
|
||||
const tryWrite = async function (withSvg) {
|
||||
const flavors = { 'text/plain': plain, 'text/html': html }
|
||||
if (withSvg) flavors['image/svg+xml'] = new Blob([svgText], { type: 'image/svg+xml' })
|
||||
await nav.clipboard.write([new Item(flavors)])
|
||||
}
|
||||
try {
|
||||
await tryWrite(svgFlavor)
|
||||
return svgFlavor ? 'svg' : 'text'
|
||||
} catch (error) {
|
||||
// 某个口味被拒会让整次写入失败:去掉矢量口味再试一次
|
||||
if (svgFlavor) {
|
||||
try {
|
||||
await tryWrite(false)
|
||||
return 'text'
|
||||
} catch (error2) { /* 落到 writeText */ }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (nav && nav.clipboard && typeof nav.clipboard.writeText === 'function') {
|
||||
await nav.clipboard.writeText(svgText)
|
||||
return 'text'
|
||||
}
|
||||
return ''
|
||||
}
|
||||
|
||||
async function copySvg(button) {
|
||||
if (!currentSvg) { setStatus('error', '还没有可复制的矢量结果'); return }
|
||||
const label = button.textContent
|
||||
button.disabled = true
|
||||
try {
|
||||
const how = await writeSvgToClipboard(currentSvg)
|
||||
if (!how) throw new Error('当前环境不允许写剪贴板')
|
||||
button.textContent = '已复制'
|
||||
setStatus('busy', how === 'svg'
|
||||
? '已复制矢量,直接粘到 Figma / Illustrator 即可'
|
||||
: '已复制 SVG 源码(粘不进去的话改用「下载 SVG」再拖入)')
|
||||
const text = els ? els.statusText.textContent : ''
|
||||
window.setTimeout(function () {
|
||||
if (els && els.statusText.textContent === text) setStatus(null)
|
||||
}, 2600)
|
||||
} catch (error) {
|
||||
setStatus('error', '复制失败:' + (error && error.message ? error.message : String(error)))
|
||||
} finally {
|
||||
window.setTimeout(function () {
|
||||
if (els) { button.disabled = false; button.textContent = label }
|
||||
}, 1200)
|
||||
}
|
||||
}
|
||||
|
||||
// ---------- 输出 ----------
|
||||
|
||||
function downloadSvg() {
|
||||
@@ -379,9 +467,11 @@ export function createVectorizer(options) {
|
||||
if (box) {
|
||||
const open = box.hidden
|
||||
box.hidden = !open
|
||||
advOpen = open
|
||||
adv.setAttribute('aria-expanded', String(open))
|
||||
const caret = adv.querySelector('[data-adv-caret]')
|
||||
if (caret) caret.textContent = open ? '▴' : '▾'
|
||||
writeSettings()
|
||||
}
|
||||
return
|
||||
}
|
||||
@@ -411,6 +501,9 @@ export function createVectorizer(options) {
|
||||
} else if (name === 'alphaTone') {
|
||||
params.alphaMax = ALPHA_TONE[value] === undefined ? 1 : ALPHA_TONE[value]
|
||||
preset = ''
|
||||
} else if (name === 'precision') {
|
||||
params.optTolerance = TOLERANCE_TONES[value] === undefined ? DEFAULTS.optTolerance : TOLERANCE_TONES[value]
|
||||
preset = ''
|
||||
} else if (name === 'invert') {
|
||||
params.invert = value === '1'
|
||||
preset = ''
|
||||
@@ -434,6 +527,7 @@ export function createVectorizer(options) {
|
||||
if (!act) return
|
||||
const name = act.dataset.act
|
||||
if (name === 'cancel') { close(); return }
|
||||
if (name === 'copy') { copySvg(act); return }
|
||||
if (name === 'svg') { downloadSvg(); return }
|
||||
if (name === 'save') { saveNode(act); return }
|
||||
}
|
||||
@@ -489,6 +583,7 @@ export function createVectorizer(options) {
|
||||
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)))
|
||||
advOpen = stored.advOpen === undefined ? true : Boolean(stored.advOpen)
|
||||
|
||||
const img = await loadImage(request.imageDataUrl)
|
||||
const name = String(request.name || 'image.png')
|
||||
@@ -511,7 +606,7 @@ export function createVectorizer(options) {
|
||||
}
|
||||
els.original.src = request.imageDataUrl
|
||||
els.meta.textContent = name + ' · ' + source.srcW + '×' + source.srcH
|
||||
els.panel.innerHTML = panelHTML(params, preset, outScale)
|
||||
els.panel.innerHTML = panelHTML(params, preset, outScale, advOpen)
|
||||
|
||||
root.addEventListener('click', onRootClick)
|
||||
els.panel.addEventListener('input', onPanelInput)
|
||||
|
||||
+105
-13
@@ -9,7 +9,7 @@
|
||||
var __IWB_VECTORIZE_MANIFEST__ = {
|
||||
id: 'image-vectorize',
|
||||
name: '位图转矢量',
|
||||
version: '0.2.0',
|
||||
version: '0.2.1',
|
||||
apiVersion: 1,
|
||||
capabilities: ['commands', 'nodeActions', 'canvas', 'canvasWrite'],
|
||||
settings: {
|
||||
@@ -19,9 +19,11 @@ var __IWB_VECTORIZE_MANIFEST__ = {
|
||||
threshold: { type: 'number', default: -1 },
|
||||
turdSize: { type: 'number', default: 3 },
|
||||
alphaMax: { type: 'number', default: 1 },
|
||||
optTolerance: { type: 'number', default: 0.05 },
|
||||
invert: { type: 'boolean', default: false },
|
||||
color: { type: 'string', default: '#1a1a1a' },
|
||||
outScale: { type: 'number', default: 2 }
|
||||
outScale: { type: 'number', default: 2 },
|
||||
advOpen: { type: 'boolean', default: true }
|
||||
},
|
||||
}
|
||||
|
||||
@@ -2000,14 +2002,14 @@ var __IWB_VECTORIZE_MANIFEST__ = {
|
||||
});
|
||||
|
||||
// image-vectorize/plugin/ui.css
|
||||
var ui_default = '/* 位图转矢量:全屏模态。深色,与「标注 / 修图」同一套视觉语言。\n CSP:由宿主 style-src \'unsafe-inline\' 放行,运行时注入 <style>。 */\n\n.vz-root {\n position: fixed;\n inset: 0;\n z-index: 2147483000;\n display: flex;\n align-items: center;\n justify-content: center;\n background: rgba(10, 10, 14, 0.72);\n font: 13px/1.5 -apple-system, BlinkMacSystemFont, "PingFang SC", "Microsoft YaHei", sans-serif;\n color: #e6e6ef;\n}\n\n.vz-modal {\n display: flex;\n flex-direction: column;\n width: 92vw;\n height: 88vh;\n min-width: 760px;\n min-height: 520px;\n max-width: 1680px;\n background: #1b1b22;\n border: 1px solid #33333f;\n border-radius: 12px;\n box-shadow: 0 24px 64px rgba(0, 0, 0, 0.55);\n overflow: hidden;\n}\n\n/* ---------- 顶栏 ---------- */\n.vz-header {\n display: flex;\n align-items: center;\n gap: 10px;\n flex: 0 0 auto;\n height: 52px;\n padding: 0 14px;\n background: #202029;\n border-bottom: 1px solid #2e2e3a;\n}\n\n.vz-title {\n font-size: 13px;\n font-weight: 500;\n color: #f0f0f7;\n white-space: nowrap;\n}\n\n.vz-title em {\n font-style: normal;\n color: #8b8b9e;\n font-weight: 400;\n margin-left: 8px;\n}\n\n.vz-title em b {\n color: #d6d6e4;\n font-weight: 500;\n}\n\n.vz-spacer { flex: 1 1 auto; }\n\n.vz-btn {\n height: 32px;\n padding: 0 14px;\n border: 1px solid #3c3c4c;\n border-radius: 7px;\n background: #2a2a35;\n color: #d8d8e4;\n font-size: 12px;\n cursor: pointer;\n white-space: nowrap;\n}\n.vz-btn:hover { background: #34343f; border-color: #4a4a5c; }\n.vz-btn:active { background: #2f2f3a; }\n.vz-btn:disabled { opacity: 0.45; cursor: default; }\n\n.vz-btn-primary {\n background: #1f7a52;\n border-color: #27875c;\n color: #eafff5;\n}\n.vz-btn-primary:hover { background: #248a5d; border-color: #2f9c69; }\n.vz-btn-primary:disabled { background: #24503e; border-color: #2a5c47; }\n\n/* ---------- 主体 ---------- */\n.vz-body {\n display: flex;\n flex: 1 1 auto;\n min-height: 0;\n}\n\n.vz-preview {\n position: relative;\n flex: 1 1 auto;\n min-width: 0;\n display: flex;\n align-items: center;\n justify-content: center;\n padding: 20px;\n overflow: hidden;\n /* 透明区用中性灰棋盘,不用深色:电商素材里大量是黑字/深色 logo,\n 深色棋盘会把这些内容直接吞掉,看起来像「描摹失败」 */\n background-color: #c8c8c8;\n background-image:\n linear-gradient(45deg, #a8a8a8 25%, transparent 25%, transparent 75%, #a8a8a8 75%),\n linear-gradient(45deg, #a8a8a8 25%, transparent 25%, transparent 75%, #a8a8a8 75%);\n background-size: 20px 20px;\n background-position: 0 0, 10px 10px;\n}\n\n.vz-stage {\n max-width: 100%;\n max-height: 100%;\n display: block;\n box-shadow: 0 4px 24px rgba(0, 0, 0, 0.35);\n}\n\n.vz-stage[hidden] { display: none; }\n\n.vz-badge {\n position: absolute;\n top: 14px;\n left: 14px;\n padding: 4px 9px;\n border-radius: 6px;\n background: rgba(18, 18, 24, 0.82);\n border: 1px solid #33333f;\n color: #a8a8bb;\n font-size: 11px;\n letter-spacing: 0.2px;\n}\n\n.vz-hint {\n position: absolute;\n bottom: 14px;\n left: 50%;\n transform: translateX(-50%);\n color: #75758a;\n font-size: 11px;\n pointer-events: none;\n white-space: nowrap;\n}\n\n/* 描摹中/出错的浮层 */\n.vz-status {\n position: absolute;\n top: 14px;\n right: 14px;\n display: flex;\n align-items: center;\n gap: 8px;\n padding: 5px 11px;\n border-radius: 7px;\n font-size: 11px;\n background: rgba(18, 18, 24, 0.88);\n border: 1px solid #33333f;\n color: #b9b9cc;\n}\n.vz-status[hidden] { display: none; }\n.vz-status.is-busy { color: #ffd08a; border-color: #5a4526; }\n.vz-status.is-error { color: #ff9c9c; border-color: #5c2c2c; max-width: 60%; }\n\n.vz-dot {\n width: 7px;\n height: 7px;\n border-radius: 50%;\n background: currentColor;\n flex: 0 0 auto;\n}\n.vz-status.is-busy .vz-dot { animation: vz-pulse 1s ease-in-out infinite; }\n@keyframes vz-pulse { 0%, 100% { opacity: 0.25; } 50% { opacity: 1; } }\n\n/* ---------- 参数面板 ---------- */\n.vz-panel {\n flex: 0 0 auto;\n width: 312px;\n padding: 14px 16px 18px;\n background: #1e1e26;\n border-left: 1px solid #2e2e3a;\n overflow-y: auto;\n}\n\n.vz-panel::-webkit-scrollbar { width: 8px; }\n.vz-panel::-webkit-scrollbar-thumb { background: #3a3a48; border-radius: 4px; }\n\n.vz-group + .vz-group { margin-top: 18px; padding-top: 16px; border-top: 1px solid #2b2b36; }\n\n.vz-group-title {\n font-size: 11px;\n color: #7e7e94;\n letter-spacing: 0.6px;\n margin-bottom: 9px;\n text-transform: none;\n}\n\n/* 预设 */\n.vz-presets {\n display: grid;\n grid-template-columns: 1fr 1fr;\n gap: 7px;\n}\n\n.vz-preset {\n display: flex;\n flex-direction: column;\n gap: 2px;\n padding: 8px 9px;\n border: 1px solid #37374a;\n border-radius: 8px;\n background: #262631;\n color: #d5d5e2;\n font-size: 12px;\n text-align: left;\n cLine truncated
|
||||
var ui_default = '/* 位图转矢量:全屏模态。深色,与「标注 / 修图」同一套视觉语言。\n CSP:由宿主 style-src \'unsafe-inline\' 放行,运行时注入 <style>。 */\n\n.vz-root {\n position: fixed;\n inset: 0;\n z-index: 2147483000;\n display: flex;\n align-items: center;\n justify-content: center;\n background: rgba(10, 10, 14, 0.72);\n font: 13px/1.5 -apple-system, BlinkMacSystemFont, "PingFang SC", "Microsoft YaHei", sans-serif;\n color: #e6e6ef;\n}\n\n.vz-modal {\n display: flex;\n flex-direction: column;\n width: 92vw;\n height: 88vh;\n min-width: 760px;\n min-height: 520px;\n max-width: 1680px;\n background: #1b1b22;\n border: 1px solid #33333f;\n border-radius: 12px;\n box-shadow: 0 24px 64px rgba(0, 0, 0, 0.55);\n overflow: hidden;\n}\n\n/* ---------- 顶栏 ---------- */\n.vz-header {\n display: flex;\n align-items: center;\n gap: 10px;\n flex: 0 0 auto;\n height: 52px;\n padding: 0 14px;\n background: #202029;\n border-bottom: 1px solid #2e2e3a;\n}\n\n.vz-title {\n font-size: 13px;\n font-weight: 500;\n color: #f0f0f7;\n white-space: nowrap;\n}\n\n.vz-title em {\n font-style: normal;\n color: #8b8b9e;\n font-weight: 400;\n margin-left: 8px;\n}\n\n.vz-title em b {\n color: #d6d6e4;\n font-weight: 500;\n}\n\n.vz-spacer { flex: 1 1 auto; }\n\n.vz-btn {\n height: 32px;\n padding: 0 14px;\n border: 1px solid #3c3c4c;\n border-radius: 7px;\n background: #2a2a35;\n color: #d8d8e4;\n font-size: 12px;\n cursor: pointer;\n white-space: nowrap;\n}\n.vz-btn:hover { background: #34343f; border-color: #4a4a5c; }\n.vz-btn:active { background: #2f2f3a; }\n.vz-btn:disabled { opacity: 0.45; cursor: default; }\n\n.vz-btn-primary {\n background: #1f7a52;\n border-color: #27875c;\n color: #eafff5;\n}\n.vz-btn-primary:hover { background: #248a5d; border-color: #2f9c69; }\n.vz-btn-primary:disabled { background: #24503e; border-color: #2a5c47; }\n\n/* ---------- 主体 ---------- */\n.vz-body {\n display: flex;\n flex: 1 1 auto;\n min-height: 0;\n}\n\n.vz-preview {\n position: relative;\n flex: 1 1 auto;\n min-width: 0;\n display: flex;\n align-items: center;\n justify-content: center;\n padding: 20px;\n overflow: hidden;\n /* 透明区用中性灰棋盘,不用深色:电商素材里大量是黑字/深色 logo,\n 深色棋盘会把这些内容直接吞掉,看起来像「描摹失败」 */\n background-color: #c8c8c8;\n background-image:\n linear-gradient(45deg, #a8a8a8 25%, transparent 25%, transparent 75%, #a8a8a8 75%),\n linear-gradient(45deg, #a8a8a8 25%, transparent 25%, transparent 75%, #a8a8a8 75%);\n background-size: 20px 20px;\n background-position: 0 0, 10px 10px;\n}\n\n.vz-stage {\n max-width: 100%;\n max-height: 100%;\n display: block;\n box-shadow: 0 4px 24px rgba(0, 0, 0, 0.35);\n}\n\n.vz-stage[hidden] { display: none; }\n\n.vz-badge {\n position: absolute;\n top: 14px;\n left: 14px;\n padding: 4px 9px;\n border-radius: 6px;\n background: rgba(18, 18, 24, 0.82);\n border: 1px solid #33333f;\n color: #a8a8bb;\n font-size: 11px;\n letter-spacing: 0.2px;\n}\n\n/* 底部提示:浅灰棋盘上 #75758a 的裸文字几乎看不见(实测),改成深色胶囊 */\n.vz-hint {\n position: absolute;\n bottom: 14px;\n left: 50%;\n transform: translateX(-50%);\n padding: 5px 11px;\n border-radius: 999px;\n background: rgba(22, 22, 30, 0.8);\n color: #dcdce8;\n font-size: 11px;\n pointer-events: none;\n white-space: nowrap;\n}\n\n/* 描摹中/出错的浮层 */\n.vz-status {\n position: absolute;\n top: 14px;\n right: 14px;\n display: flex;\n align-items: center;\n gap: 8px;\n padding: 5px 11px;\n border-radius: 7px;\n font-size: 11px;\n background: rgba(18, 18, 24, 0.88);\n border: 1px solid #33333f;\n color: #b9b9cc;\n}\n.vz-status[hidden] { display: none; }\n.vz-status.is-busy { color: #ffd08a; border-color: #5a4526; }\n.vz-status.is-error { color: #ff9c9c; border-color: #5c2c2c; max-width: 60%; }\n\n.vz-dot {\n width: 7px;\n height: 7px;\n border-radius: 50%;\n background: currentColor;\n flex: 0 0 auto;\n}\n.vz-status.is-busy .vz-dot { animation: vz-pulse 1s ease-in-out infinite; }\n@keyframes vz-pulse { 0%, 100% { opacity: 0.25; } 50% { opacity: 1; } }\n\n/* ---------- 参数面板 ---------- */\n.vz-panel {\n flex: 0 0 auto;\n width: 312px;\n padding: 12px 15px 14px;\n background: #1e1e26;\n border-left: 1px solid #2e2e3a;\n overflow-y: auto;\n}\n\n.vz-panel::-webkit-scrollbar { width: 8px; }\n.vz-panel::-webkit-scrollbar-thumb { background: #3a3a48; border-radius: 4px; }\n\n.vz-group + .vz-group { margin-top: 14px; padding-top: 12px; border-top: 1px solid #2b2b36; }\n\n.vz-group-title {\n font-size: 11px;\n color: #7e7e94;\n letter-spacing: 0.6px;\n margin-bottom: 9px;\n text-transform: none;\n}\n\n/* 预设 */\n.vz-presets {\n display: grid;\n grid-template-columns: 1fr 1fr;\n gap: 7px;\n}\n\n.vz-preset {\n display: flex;\n flex-diLine truncated
|
||||
|
||||
// image-vectorize/plugin/engine.js
|
||||
var import_Potrace = __toESM(require_Potrace());
|
||||
var import_Posterizer = __toESM(require_Posterizer());
|
||||
var LEVELS_MIN = 2;
|
||||
var LEVELS_MAX = 5;
|
||||
var MAX_TRACE_SIDE = 2e3;
|
||||
var MAX_TRACE_SIDE = 3e3;
|
||||
var DEFAULTS = {
|
||||
mode: "gray",
|
||||
// 'gray' 灰度分层 / 'mono' 纯单色
|
||||
@@ -2018,7 +2020,11 @@ var __IWB_VECTORIZE_MANIFEST__ = {
|
||||
turdSize: 3,
|
||||
// 去小点:面积小于它的碎片直接丢(毛刺/噪点克星)
|
||||
alphaMax: 1,
|
||||
// 拐角平滑:0 全折线、1 默认、1.334 最圆
|
||||
// 拐角阈值:0 全折线、1 默认、1.334 最圆
|
||||
// 曲线拟合容差(越小越贴合原图像素边缘,路径数据也越大)。
|
||||
// 上游默认 0.2 是「视觉上够用」的省数据值;实测 0.2 在文字笔画与圆角处会
|
||||
// 吃掉约半个像素的弯折,所以这里默认降到 0.05(用户 2026-11-05 要求「边缘精度再高一点」)。
|
||||
optTolerance: 0.05,
|
||||
invert: false,
|
||||
// 反相:描摹亮部(黑底白字场景)
|
||||
color: "#1a1a1a",
|
||||
@@ -2026,6 +2032,7 @@ var __IWB_VECTORIZE_MANIFEST__ = {
|
||||
outScale: 1
|
||||
// 输出尺寸倍率(只放大尺寸,不重算曲线)
|
||||
};
|
||||
var TOLERANCE_TONES = { fine: 0.05, normal: 0.15, light: 0.4 };
|
||||
var clampInt = (v, min, max, dflt) => {
|
||||
const n = Math.round(Number(v));
|
||||
return Number.isFinite(n) ? Math.min(max, Math.max(min, n)) : dflt;
|
||||
@@ -2041,6 +2048,10 @@ var __IWB_VECTORIZE_MANIFEST__ = {
|
||||
const n = Number(src.alphaMax);
|
||||
return Number.isFinite(n) ? Math.min(1.334, Math.max(0, n)) : DEFAULTS.alphaMax;
|
||||
})(),
|
||||
optTolerance: (() => {
|
||||
const n = Number(src.optTolerance);
|
||||
return Number.isFinite(n) ? Math.min(2, Math.max(0.01, n)) : DEFAULTS.optTolerance;
|
||||
})(),
|
||||
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))
|
||||
@@ -2106,7 +2117,7 @@ var __IWB_VECTORIZE_MANIFEST__ = {
|
||||
turdSize: p.turdSize,
|
||||
alphaMax: p.alphaMax,
|
||||
optCurve: true,
|
||||
optTolerance: 0.2,
|
||||
optTolerance: p.optTolerance,
|
||||
blackOnWhite: !p.invert,
|
||||
color: p.color
|
||||
});
|
||||
@@ -2122,7 +2133,7 @@ var __IWB_VECTORIZE_MANIFEST__ = {
|
||||
turdSize: p.turdSize,
|
||||
alphaMax: p.alphaMax,
|
||||
optCurve: true,
|
||||
optTolerance: 0.2,
|
||||
optTolerance: p.optTolerance,
|
||||
blackOnWhite: !p.invert,
|
||||
fillStrategy: "median",
|
||||
// 灰度:每层取该层亮度中位数
|
||||
@@ -2207,7 +2218,7 @@ var __IWB_VECTORIZE_MANIFEST__ = {
|
||||
}
|
||||
|
||||
// image-vectorize/plugin/ui.js
|
||||
var SETTING_KEYS = ["preset", "mode", "levels", "threshold", "turdSize", "alphaMax", "invert", "color", "outScale"];
|
||||
var SETTING_KEYS = ["preset", "mode", "levels", "threshold", "turdSize", "alphaMax", "optTolerance", "invert", "color", "outScale", "advOpen"];
|
||||
var PRESETS = {
|
||||
text: { label: "文字 / 线稿", hint: "单色 · 保笔画", mode: "mono", turdSize: 2, alphaMax: 1, levels: 3 },
|
||||
menu: { label: "菜单 / 图文", hint: "灰度 3 层", mode: "gray", levels: 3, turdSize: 4, alphaMax: 1 },
|
||||
@@ -2231,22 +2242,23 @@ var __IWB_VECTORIZE_MANIFEST__ = {
|
||||
function rangeHTML(name, label, min, max, step, value, hint) {
|
||||
return '<div class="vz-row"><div class="vz-row-label">' + esc(label) + (hint ? "<span>" + esc(hint) + "</span>" : "") + '</div><div class="vz-range"><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, outScale) {
|
||||
function panelHTML(params, preset, outScale, advOpen) {
|
||||
const presets = Object.keys(PRESETS).map(function(key) {
|
||||
const p = PRESETS[key];
|
||||
return '<button type="button" class="vz-preset' + (key === preset ? " active" : "") + '" data-preset="' + key + '">' + esc(p.label) + "<small>" + esc(p.hint) + "</small></button>";
|
||||
}).join("");
|
||||
return '<div class="vz-group"><div class="vz-group-title">预设</div><div class="vz-presets">' + presets + '</div></div><div class="vz-group"><div class="vz-row"><div class="vz-row-label">描摹方式</div><div class="vz-seg" data-seg-group="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><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) {
|
||||
}).join("") + '</div></div></div><div class="vz-group">' + rangeHTML("turdSize", "去小点", 0, 40, 1, params.turdSize, HINTS.turdSize) + '<div class="vz-row"><div class="vz-row-label">边缘<span>拐角处理</span></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 class="vz-row"><div class="vz-row-label">精度<span>越高越贴合原图,曲线数据略多</span></div><div class="vz-seg" data-seg-group="precision"><button type="button" data-seg="precision" data-value="fine">精细</button><button type="button" data-seg="precision" data-value="normal">标准</button><button type="button" data-seg="precision" data-value="light">轻量</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><div class="vz-group"><div class="vz-stats"><span><b data-stat="paths">–</b> 路径</span><span><b data-stat="levels">–</b> 层</span><span><b data-stat="bytes">–</b></span><span><b data-stat="ms">–</b></span></div></div><div class="vz-group"><button type="button" class="vz-adv-toggle" data-act="adv" aria-expanded="false">高级参数<span data-adv-caret>▾</span></button><div class="vz-adv" data-adv hidden><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>';
|
||||
}).join("") + '</div></div></div><div class="vz-group"><div class="vz-stats"><span><b data-stat="paths">–</b> 路径</span><span><b data-stat="levels">–</b> 层</span><span><b data-stat="bytes">–</b></span><span><b data-stat="ms">–</b></span></div></div><div class="vz-group"><button type="button" class="vz-adv-toggle" data-act="adv" aria-expanded="' + (advOpen ? "true" : "false") + '">高级参数<span data-adv-caret>' + (advOpen ? "▴" : "▾") + '</span></button><div class="vz-adv" data-adv' + (advOpen ? "" : " hidden") + '><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></div>';
|
||||
}
|
||||
function viewHTML(name) {
|
||||
return '<div class="vz-root"><div class="vz-modal" role="dialog" aria-modal="true" aria-label="位图转矢量"><header class="vz-header"><span class="vz-title">位图转矢量<em data-meta>' + esc(name) + '</em></span><div class="vz-spacer"></div><button type="button" class="vz-btn" data-act="cancel">取消</button><button type="button" class="vz-btn" data-act="svg">下载 SVG</button><button type="button" class="vz-btn vz-btn-primary" data-act="save">保存为节点</button></header><div class="vz-body"><div class="vz-preview"><img class="vz-stage" data-stage="vector" alt="矢量预览"><img class="vz-stage" data-stage="original" alt="原图" hidden><div class="vz-badge" data-badge>矢量预览</div><div class="vz-status" data-status hidden><i class="vz-dot"></i><span data-status-text></span></div><div class="vz-hint">按住空格键对比原图</div></div><aside class="vz-panel" data-panel></aside></div></div></div>';
|
||||
return '<div class="vz-root"><div class="vz-modal" role="dialog" aria-modal="true" aria-label="位图转矢量"><header class="vz-header"><span class="vz-title">位图转矢量<em data-meta>' + esc(name) + '</em></span><div class="vz-spacer"></div><button type="button" class="vz-btn" data-act="cancel">取消</button><button type="button" class="vz-btn" data-act="copy">复制 SVG</button><button type="button" class="vz-btn" data-act="svg">下载 SVG</button><button type="button" class="vz-btn vz-btn-primary" data-act="save">保存为节点</button></header><div class="vz-body"><div class="vz-preview"><img class="vz-stage" data-stage="vector" alt="矢量预览"><img class="vz-stage" data-stage="original" alt="原图" hidden><div class="vz-badge" data-badge>矢量预览</div><div class="vz-status" data-status hidden><i class="vz-dot"></i><span data-status-text></span></div><div class="vz-hint">空格 对比原图 · 「复制 SVG」可直接粘到 Figma</div></div><aside class="vz-panel" data-panel></aside></div></div></div>';
|
||||
}
|
||||
var ALPHA_TONE = { hard: 0.4, normal: 1, round: 1.2 };
|
||||
var toneOf = (alphaMax) => alphaMax <= 0.6 ? "hard" : alphaMax >= 1.1 ? "round" : "normal";
|
||||
var tolToneOf = (tol) => tol <= 0.08 ? "fine" : tol >= 0.3 ? "light" : "normal";
|
||||
function createVectorizer(options) {
|
||||
const settings = options.settings;
|
||||
const onSaveNode = options.onSaveNode;
|
||||
@@ -2258,6 +2270,7 @@ var __IWB_VECTORIZE_MANIFEST__ = {
|
||||
let params = normalizeParams(DEFAULTS);
|
||||
let preset = "text";
|
||||
let outScale = 2;
|
||||
let advOpen = true;
|
||||
let currentSvg = "";
|
||||
let currentBlobUrl = "";
|
||||
let seq = 0;
|
||||
@@ -2275,6 +2288,7 @@ var __IWB_VECTORIZE_MANIFEST__ = {
|
||||
}
|
||||
if (value === void 0 || value === null || value === "") continue;
|
||||
if (key === "invert") value = value === true || value === "true" || value === 1 || value === "1";
|
||||
if (key === "advOpen") value = !(value === false || value === "false" || value === 0 || value === "0");
|
||||
out[key] = value;
|
||||
}
|
||||
return out;
|
||||
@@ -2288,9 +2302,11 @@ var __IWB_VECTORIZE_MANIFEST__ = {
|
||||
settings.set("threshold", params.threshold);
|
||||
settings.set("turdSize", params.turdSize);
|
||||
settings.set("alphaMax", params.alphaMax);
|
||||
settings.set("optTolerance", params.optTolerance);
|
||||
settings.set("invert", params.invert);
|
||||
settings.set("color", params.color);
|
||||
settings.set("outScale", outScale);
|
||||
settings.set("advOpen", advOpen);
|
||||
} catch (e) {
|
||||
}
|
||||
}
|
||||
@@ -2348,6 +2364,9 @@ var __IWB_VECTORIZE_MANIFEST__ = {
|
||||
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="precision"] button').forEach(function(btn) {
|
||||
btn.classList.toggle("active", btn.dataset.value === tolToneOf(params.optTolerance));
|
||||
});
|
||||
panel.querySelectorAll('[data-seg-group="invert"] button').forEach(function(btn) {
|
||||
btn.classList.toggle("active", btn.dataset.value === "1" === params.invert);
|
||||
});
|
||||
@@ -2423,6 +2442,69 @@ var __IWB_VECTORIZE_MANIFEST__ = {
|
||||
retrace();
|
||||
}, 120);
|
||||
}
|
||||
async function writeSvgToClipboard(svgText) {
|
||||
const nav = typeof navigator === "undefined" ? null : navigator;
|
||||
const Item = typeof window === "undefined" ? null : window.ClipboardItem;
|
||||
const plain = new Blob([svgText], { type: "text/plain" });
|
||||
const html = new Blob([svgText], { type: "text/html" });
|
||||
let svgFlavor = false;
|
||||
if (nav && nav.clipboard && typeof nav.clipboard.write === "function" && typeof Item === "function") {
|
||||
try {
|
||||
svgFlavor = typeof Item.supports !== "function" || Item.supports("image/svg+xml");
|
||||
} catch (e) {
|
||||
svgFlavor = false;
|
||||
}
|
||||
const tryWrite = async function(withSvg) {
|
||||
const flavors = { "text/plain": plain, "text/html": html };
|
||||
if (withSvg) flavors["image/svg+xml"] = new Blob([svgText], { type: "image/svg+xml" });
|
||||
await nav.clipboard.write([new Item(flavors)]);
|
||||
};
|
||||
try {
|
||||
await tryWrite(svgFlavor);
|
||||
return svgFlavor ? "svg" : "text";
|
||||
} catch (error) {
|
||||
if (svgFlavor) {
|
||||
try {
|
||||
await tryWrite(false);
|
||||
return "text";
|
||||
} catch (error2) {
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
if (nav && nav.clipboard && typeof nav.clipboard.writeText === "function") {
|
||||
await nav.clipboard.writeText(svgText);
|
||||
return "text";
|
||||
}
|
||||
return "";
|
||||
}
|
||||
async function copySvg(button) {
|
||||
if (!currentSvg) {
|
||||
setStatus("error", "还没有可复制的矢量结果");
|
||||
return;
|
||||
}
|
||||
const label = button.textContent;
|
||||
button.disabled = true;
|
||||
try {
|
||||
const how = await writeSvgToClipboard(currentSvg);
|
||||
if (!how) throw new Error("当前环境不允许写剪贴板");
|
||||
button.textContent = "已复制";
|
||||
setStatus("busy", how === "svg" ? "已复制矢量,直接粘到 Figma / Illustrator 即可" : "已复制 SVG 源码(粘不进去的话改用「下载 SVG」再拖入)");
|
||||
const text = els ? els.statusText.textContent : "";
|
||||
window.setTimeout(function() {
|
||||
if (els && els.statusText.textContent === text) setStatus(null);
|
||||
}, 2600);
|
||||
} catch (error) {
|
||||
setStatus("error", "复制失败:" + (error && error.message ? error.message : String(error)));
|
||||
} finally {
|
||||
window.setTimeout(function() {
|
||||
if (els) {
|
||||
button.disabled = false;
|
||||
button.textContent = label;
|
||||
}
|
||||
}, 1200);
|
||||
}
|
||||
}
|
||||
function downloadSvg() {
|
||||
if (!currentSvg) {
|
||||
setStatus("error", "还没有可下载的矢量结果");
|
||||
@@ -2489,9 +2571,11 @@ var __IWB_VECTORIZE_MANIFEST__ = {
|
||||
if (box) {
|
||||
const open2 = box.hidden;
|
||||
box.hidden = !open2;
|
||||
advOpen = open2;
|
||||
adv.setAttribute("aria-expanded", String(open2));
|
||||
const caret = adv.querySelector("[data-adv-caret]");
|
||||
if (caret) caret.textContent = open2 ? "▴" : "▾";
|
||||
writeSettings();
|
||||
}
|
||||
return;
|
||||
}
|
||||
@@ -2519,6 +2603,9 @@ var __IWB_VECTORIZE_MANIFEST__ = {
|
||||
} else if (name === "alphaTone") {
|
||||
params.alphaMax = ALPHA_TONE[value] === void 0 ? 1 : ALPHA_TONE[value];
|
||||
preset = "";
|
||||
} else if (name === "precision") {
|
||||
params.optTolerance = TOLERANCE_TONES[value] === void 0 ? DEFAULTS.optTolerance : TOLERANCE_TONES[value];
|
||||
preset = "";
|
||||
} else if (name === "invert") {
|
||||
params.invert = value === "1";
|
||||
preset = "";
|
||||
@@ -2544,6 +2631,10 @@ var __IWB_VECTORIZE_MANIFEST__ = {
|
||||
close();
|
||||
return;
|
||||
}
|
||||
if (name === "copy") {
|
||||
copySvg(act);
|
||||
return;
|
||||
}
|
||||
if (name === "svg") {
|
||||
downloadSvg();
|
||||
return;
|
||||
@@ -2601,6 +2692,7 @@ var __IWB_VECTORIZE_MANIFEST__ = {
|
||||
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)));
|
||||
advOpen = stored.advOpen === void 0 ? true : Boolean(stored.advOpen);
|
||||
const img = await loadImage(request.imageDataUrl);
|
||||
const name = String(request.name || "image.png");
|
||||
const base = name.replace(/\.[^.]+$/, "") || "image";
|
||||
@@ -2621,7 +2713,7 @@ var __IWB_VECTORIZE_MANIFEST__ = {
|
||||
};
|
||||
els.original.src = request.imageDataUrl;
|
||||
els.meta.textContent = name + " · " + source.srcW + "×" + source.srcH;
|
||||
els.panel.innerHTML = panelHTML(params, preset, outScale);
|
||||
els.panel.innerHTML = panelHTML(params, preset, outScale, advOpen);
|
||||
root.addEventListener("click", onRootClick);
|
||||
els.panel.addEventListener("input", onPanelInput);
|
||||
els.panel.addEventListener("click", onPanelClick);
|
||||
|
||||
@@ -51,7 +51,14 @@ const poll = async (fn, timeout = 25000, step = 250) => {
|
||||
|
||||
console.log('目标站点:' + BASE + '(期望插件版本 ' + WANT_VERSION + ')')
|
||||
const browser = await chromium.launch()
|
||||
const page = await browser.newPage({ viewport: { width: 1440, height: 1000 } })
|
||||
// 剪贴板要显式授权(真站是 https,安全上下文成立;本地 file/about:blank 测不到这条)
|
||||
const context = await browser.newContext({ viewport: { width: 1440, height: 1000 } })
|
||||
try {
|
||||
await context.grantPermissions(['clipboard-read', 'clipboard-write'], { origin: new URL(BASE).origin })
|
||||
} catch (error) {
|
||||
console.log('(剪贴板授权失败,相关断言会跳过:' + (error && error.message) + ')')
|
||||
}
|
||||
const page = await context.newPage()
|
||||
const consoleErrors = []
|
||||
page.on('console', (m) => { if (m.type() === 'error') consoleErrors.push(m.text()) })
|
||||
page.on('pageerror', (e) => consoleErrors.push('pageerror: ' + e.message))
|
||||
@@ -150,6 +157,37 @@ const stats = await page.evaluate(() => ({
|
||||
}))
|
||||
check('灰度层数正常(3 层)', stats.levels >= 3, JSON.stringify(stats))
|
||||
|
||||
// ---------- 5.5) 面板形态:高级默认打开 + 精度默认精细 ----------
|
||||
check('高级参数默认展开', await page.evaluate(() => {
|
||||
const box = document.querySelector('[data-adv]')
|
||||
return Boolean(box && !box.hidden)
|
||||
}))
|
||||
check('精度默认「精细」', await page.evaluate(() => {
|
||||
const a = document.querySelector('[data-seg-group="precision"] button.active')
|
||||
return Boolean(a && a.dataset.value === 'fine')
|
||||
}))
|
||||
|
||||
// ---------- 5.6) 复制到剪贴板(真写,读回校验口味) ----------
|
||||
await page.locator('[data-act="copy"]').click()
|
||||
await sleep(400)
|
||||
const clip = await page.evaluate(async () => {
|
||||
try {
|
||||
const items = await navigator.clipboard.read()
|
||||
const types = items[0] ? items[0].types : []
|
||||
let svg = ''
|
||||
if (types.indexOf('image/svg+xml') >= 0) svg = await (await items[0].getType('image/svg+xml')).text()
|
||||
return { types, svg, status: (document.querySelector('[data-status-text]') || {}).textContent || '' }
|
||||
} catch (e) { return { error: String(e && e.message) } }
|
||||
})
|
||||
if (clip.error) {
|
||||
check('复制 SVG 写入剪贴板', false, clip.error)
|
||||
} else {
|
||||
check('复制 SVG:剪贴板含 image/svg+xml(Figma 按矢量粘贴)',
|
||||
clip.types.indexOf('image/svg+xml') >= 0 && clip.svg.indexOf('<svg') === 0 && clip.svg.indexOf('<path') > 0,
|
||||
clip.types.join(',') + ' / ' + clip.svg.length + 'B')
|
||||
check('复制后给了反馈', /已复制/.test(clip.status), clip.status)
|
||||
}
|
||||
|
||||
// ---------- 6) 保存为节点(真实画布桥) ----------
|
||||
await page.locator('[data-act="save"]').click()
|
||||
const saved = await poll(async () => (await page.locator('.iwb-node').count()) >= 2, 25000)
|
||||
|
||||
@@ -137,15 +137,27 @@ check('产物可执行(IIFE 打包 + 注册成功)', boot.version === WANT_V
|
||||
check('注册了节点动作与命令', boot.actions.includes('vectorize-node') && boot.commands.includes('vectorize-selected'), boot.actions.join(','))
|
||||
// 图标不能与别的插件撞车:'vector-square' 是 white-bg-800 的,两个插件同屏时认不出谁是谁(用户实测反馈过)
|
||||
check('节点动作图标是钢笔笔头(不与 white-bg-800 的 vector-square 重复)', boot.icons.indexOf('pen-tool') >= 0 && boot.icons.indexOf('vector-square') < 0, boot.icons.join(','))
|
||||
check('manifest 声明了参数记忆项', ['mode', 'levels', 'turdSize', 'alphaMax', 'invert', 'color', 'outScale'].every((k) => boot.settings.includes(k)), boot.settings.length + ' 项')
|
||||
check('manifest 声明了参数记忆项', ['mode', 'levels', 'turdSize', 'alphaMax', 'optTolerance', 'invert', 'color', 'outScale', 'advOpen'].every((k) => boot.settings.includes(k)), boot.settings.length + ' 项')
|
||||
check('capabilities 含 canvasWrite(要写回节点)', boot.capabilities.includes('canvasWrite'), boot.capabilities.join(','))
|
||||
|
||||
// ---------- 打开模态 ----------
|
||||
await page.evaluate(() => { window.__actions['vectorize-node'].run({ id: 'r1', type: 'ref', name: 'src.png' }) })
|
||||
await page.locator('.vz-modal').waitFor({ state: 'visible', timeout: 15000 })
|
||||
check('模态打开:预览区 + 参数面板 + 三个动作按钮齐全', await page.evaluate(() =>
|
||||
check('模态打开:预览区 + 参数面板 + 四个动作按钮齐全', await page.evaluate(() =>
|
||||
Boolean(document.querySelector('.vz-preview') && document.querySelector('.vz-panel') &&
|
||||
document.querySelector('[data-act="save"]') && document.querySelector('[data-act="svg"]') && document.querySelector('[data-act="cancel"]'))))
|
||||
document.querySelector('[data-act="save"]') && document.querySelector('[data-act="svg"]') &&
|
||||
document.querySelector('[data-act="copy"]') && document.querySelector('[data-act="cancel"]'))))
|
||||
|
||||
// 高级参数默认展开:用户 2026-11-05 明确要求「不用隐藏」(低频项也一眼能看到)
|
||||
check('高级参数默认展开', await page.evaluate(() => {
|
||||
const box = document.querySelector('[data-adv]')
|
||||
const toggle = document.querySelector('[data-act="adv"]')
|
||||
return Boolean(box && !box.hidden && toggle && toggle.getAttribute('aria-expanded') === 'true')
|
||||
}))
|
||||
check('精度档默认「精细」(optTolerance 0.05)', await page.evaluate(() => {
|
||||
const active = document.querySelector('[data-seg-group="precision"] button.active')
|
||||
return Boolean(active && active.dataset.value === 'fine')
|
||||
}))
|
||||
|
||||
const p0 = await waitText(page, '[data-stat="paths"]')
|
||||
check('纯 JS 引擎在宿主 CSP 下跑通(无需 wasm-unsafe-eval)', Boolean(p0), 'paths=' + p0)
|
||||
@@ -210,9 +222,21 @@ check('边缘「圆润」触发重新描摹(换了一套几何)', (await pag
|
||||
await page.locator('[data-seg="alphaTone"][data-value="normal"]').click()
|
||||
await sleep(400)
|
||||
|
||||
// ---------- 精度(optTolerance) ----------
|
||||
const beforeTol = await page.evaluate(() => ({ seq: window.__svgSeq, len: (window.__lastSvg || '').length }))
|
||||
await page.locator('[data-seg="precision"][data-value="light"]').click()
|
||||
await sleep(500)
|
||||
const lightTol = await page.evaluate(() => ({ seq: window.__svgSeq, len: (window.__lastSvg || '').length }))
|
||||
check('精度「轻量」重算几何且路径数据更少', lightTol.seq > beforeTol.seq && lightTol.len < beforeTol.len,
|
||||
beforeTol.len + 'B → ' + lightTol.len + 'B')
|
||||
await page.locator('[data-seg="precision"][data-value="fine"]').click()
|
||||
await sleep(500)
|
||||
const fineTol = await page.evaluate(() => (window.__lastSvg || '').length)
|
||||
check('精度「精细」路径数据更多(拟合容差真的换了)', fineTol > lightTol.len, lightTol.len + 'B → ' + fineTol + 'B')
|
||||
|
||||
// ---------- 反相 ----------
|
||||
const beforeInv = await page.evaluate(() => window.__svgSeq)
|
||||
await page.locator('[data-act="adv"]').click()
|
||||
// 高级区默认已展开(上面断言过),这里直接点反相,不再先点开
|
||||
await page.locator('[data-seg="invert"][data-value="1"]').click()
|
||||
await sleep(450)
|
||||
check('反相(负片)重新描摹', (await page.evaluate(() => window.__svgSeq)) > beforeInv)
|
||||
@@ -245,6 +269,40 @@ await sleep(400)
|
||||
check('改单色填充色写进 SVG', await page.evaluate(() => /#c0392b/i.test(window.__lastSvg || '')), '')
|
||||
|
||||
// ---------- 输出 ----------
|
||||
// 复制到剪贴板:about:blank 是非安全上下文,没有真的 Clipboard API,
|
||||
// 这里打桩只为验证「写的是哪些口味、内容是不是当前矢量」。
|
||||
await page.evaluate(() => {
|
||||
window.__clip = null
|
||||
window.__clipText = ''
|
||||
function FakeClipboardItem(items) { this.items = items }
|
||||
FakeClipboardItem.supports = function () { return true }
|
||||
Object.defineProperty(window, 'ClipboardItem', { configurable: true, writable: true, value: FakeClipboardItem })
|
||||
Object.defineProperty(navigator, 'clipboard', {
|
||||
configurable: true,
|
||||
value: {
|
||||
write: async function (items) { window.__clip = items[0].items },
|
||||
writeText: async function (text) { window.__clipText = text },
|
||||
},
|
||||
})
|
||||
})
|
||||
await page.locator('[data-act="copy"]').click()
|
||||
await sleep(400)
|
||||
const clip = await page.evaluate(async () => {
|
||||
const box = window.__clip || {}
|
||||
return {
|
||||
types: Object.keys(box),
|
||||
svg: box['image/svg+xml'] ? await box['image/svg+xml'].text() : '',
|
||||
plain: box['text/plain'] ? await box['text/plain'].text() : '',
|
||||
status: (document.querySelector('[data-status-text]') || {}).textContent || '',
|
||||
}
|
||||
})
|
||||
check('「复制 SVG」写进剪贴板(image/svg+xml + text/plain 双口味)',
|
||||
clip.types.indexOf('image/svg+xml') >= 0 && clip.types.indexOf('text/plain') >= 0 &&
|
||||
clip.svg.indexOf('<svg') >= 0 && clip.svg.indexOf('<path') >= 0,
|
||||
clip.types.join(','))
|
||||
check('复制的内容就是当前矢量(纯文本口味与矢量口味一致)', clip.plain === clip.svg && clip.plain.length > 100, clip.plain.length + 'B')
|
||||
check('复制后给用户反馈', /已复制/.test(clip.status), clip.status)
|
||||
|
||||
const dl = page.waitForEvent('download', { timeout: 8000 })
|
||||
await page.locator('[data-act="svg"]').click()
|
||||
const download = await dl
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
// 单色/灰度描摹 CLI(开发用,不进 CI):把真实素材丢进去,直接看参数效果。
|
||||
//
|
||||
// node image-vectorize/tools/trace-cli.mjs <图片> [--mode mono|gray] [--levels 3]
|
||||
// [--turd 3] [--alpha 1] [--invert] [--color #1a1a1a] [--threshold -1] [--out 目录]
|
||||
// [--turd 3] [--alpha 1] [--tol 0.1] [--invert] [--color #1a1a1a] [--threshold -1] [--out 目录]
|
||||
//
|
||||
// 产物:<out>/<name>-<mode><levels>.svg + 一张对比图 <out>/<name>-cmp.png(原图 / 结果 / 局部放大)。
|
||||
// 为什么走浏览器:PNG/JPEG 解码和 ImageData 语义都与线上一致,Node 里没有等价的零依赖解码器。
|
||||
@@ -31,13 +31,14 @@ if (!chromium) {
|
||||
|
||||
const argv = process.argv.slice(2)
|
||||
const files = []
|
||||
const opt = { mode: 'gray', levels: 3, turd: 3, alpha: 1, invert: false, color: '#1a1a1a', threshold: -1, out: '/tmp/vz-cli' }
|
||||
const opt = { mode: 'gray', levels: 3, turd: 3, alpha: 1, tol: 0.1, invert: false, color: '#1a1a1a', threshold: -1, out: '/tmp/vz-cli' }
|
||||
for (let i = 0; i < argv.length; i++) {
|
||||
const a = argv[i]
|
||||
if (a === '--mode') opt.mode = argv[++i]
|
||||
else if (a === '--levels') opt.levels = Number(argv[++i])
|
||||
else if (a === '--turd') opt.turd = Number(argv[++i])
|
||||
else if (a === '--alpha') opt.alpha = Number(argv[++i])
|
||||
else if (a === '--tol') opt.tol = Number(argv[++i])
|
||||
else if (a === '--invert') opt.invert = true
|
||||
else if (a === '--color') opt.color = argv[++i]
|
||||
else if (a === '--threshold') opt.threshold = Number(argv[++i])
|
||||
@@ -63,6 +64,7 @@ const params = {
|
||||
levels: opt.levels,
|
||||
turdSize: opt.turd,
|
||||
alphaMax: opt.alpha,
|
||||
optTolerance: opt.tol,
|
||||
invert: opt.invert,
|
||||
color: opt.color,
|
||||
threshold: opt.threshold,
|
||||
@@ -89,7 +91,7 @@ for (const file of files) {
|
||||
{ dataUrl: `data:${mime};base64,${b64}`, params }
|
||||
)
|
||||
const base = path.basename(file).replace(/\.[^.]+$/, '')
|
||||
const tag = opt.mode === 'mono' ? 'mono' : 'gray' + res.levels
|
||||
const tag = (opt.mode === 'mono' ? 'mono' : 'gray' + res.levels) + '-t' + opt.tol
|
||||
const svgPath = path.join(opt.out, `${base}-${tag}.svg`)
|
||||
fs.writeFileSync(svgPath, res.svg)
|
||||
console.log(
|
||||
|
||||
Reference in new issue
Block a user