feat(image-vectorize): v0.2 换 potrace 引擎,只做单色/灰度
用户裁定「只要单色/灰度就够」后重做:VTracer(彩色分层 wasm)换成 potrace (纯 JS,Inkscape 同款内核)。文字笔画完整、turdSize 去掉毛刺、灰度层数 2–5。 - 纯 JS ⇒ 不需要宿主放宽 CSP;插件 238KB → 116KB - 自带 potrace 移植(GPL-2.0,去 jimp 依赖,改吃 ImageData),License 随目录 - 灰度阈值自己按等像素量分位算(上游 steps:5 要 28s,这里几十 ms), 并处理「主背景峰要排除」「切点必须严格递增」两个坑 - 新增 tools/trace-cli.mjs:拿真实素材直接跑参数、出对比图 - harness 重写 32 项(含「无 wasm-unsafe-eval 的 CSP 下跑通」反向锁);真站 e2e 13 项
This commit is contained in:
1 parent
6f3a4676bb
commit
c4e4b15375
29 files changed
+5949
-2321
No files matched your search
@@ -1,9 +1,9 @@
|
||||
# 简化版 PS(Image Editor Lite)目标与实施分析
|
||||
|
||||
> 基线:`image-annotate` v1.0.5(`plugin-image-annotate.cfecb6e2ec17.js`),宿主 `image-workbench-web` 插件 API v1。
|
||||
> 基线:`image-annotate` v1.0.5(`plugin-image-annotate.cfecb6e2ec17.js`),宿主 `image-workbench-web` 插件 API v1。
|
||||
> 本文只做目标定义、差距分析、UI/架构/分期设计,**不含代码改动**。改动前先确认文末「待拍板」一节。
|
||||
>
|
||||
> **范围裁定(用户确认)**:只做**单张图片**的编辑与输出,**不做批量出图 / 多图队列 / 批量导出**;
|
||||
> **范围裁定(用户确认)**:只做**单张图片**的编辑与输出,**不做批量出图 / 多图队列 / 批量导出**;
|
||||
> UI 以「**便利 / 顺手**」为第一目标,不以「像 PS」为目标 —— 菜单层级、弹窗、确认步骤能省则省。
|
||||
>
|
||||
> **决策裁定(2026-11-04)**:① 选区 `Delete` **只作用当前图层**;②「清空标注」=**全部还原到打开时的原图**(删掉所有非原图图层 + 清掉所有绘制/变换,且可撤销);③ **≤500KB 做成输出预设**(不默认产两个文件);④ **浮动操作条先实现、上线后由用户实际体验再裁定**保留/调整/移除,本轮不因「待体验」而停工。详见 §8。
|
||||
@@ -14,14 +14,14 @@
|
||||
|
||||
现在的插件是一个**功能很强的标注器**,但还不是一个**图像编辑器**。差距不在「工具数量少」(已有 11 个工具),而在三根缺失的柱子:
|
||||
|
||||
| 柱子 | 现状 | 对齐目标后 |
|
||||
| --- | --- | --- |
|
||||
| 选区 | 只有裁剪框(`S.cropRect`)和钢笔路径,没有「可作用于像素的选区」 | 框选 → 复制/剪切到新层 / 清除 / 填充 / 限制画笔 |
|
||||
| 非破坏性 | `confirmCrop()` 把所有可见层 flatten 成一张图,并清空撤销栈 | 裁剪、变换、图层结构都可撤销;导出时才合成 |
|
||||
| 输出工作流 | 只有 PNG Blob → 覆盖/新建节点 | 单张:格式、尺寸、背景、体积上限、下载/剪贴板可配置 |
|
||||
| 柱子 | 现状 | 对齐目标后 |
|
||||
| ----- | ------------------------------------------ | ------------------------------ |
|
||||
| 选区 | 只有裁剪框(`S.cropRect`)和钢笔路径,没有「可作用于像素的选区」 | 框选 → 复制/剪切到新层 / 清除 / 填充 / 限制画笔 |
|
||||
| 非破坏性 | `confirmCrop()` 把所有可见层 flatten 成一张图,并清空撤销栈 | 裁剪、变换、图层结构都可撤销;导出时才合成 |
|
||||
| 输出工作流 | 只有 PNG Blob → 覆盖/新建节点 | 单张:格式、尺寸、背景、体积上限、下载/剪贴板可配置 |
|
||||
|
||||
建议路径:**先重做地基与 UI(P0)→ 上选区(P1)→ 修裁剪/画布(P2)→ 图层增强(P3)→ 输出工作流(P4)**。
|
||||
不要直接往现有 `events.js` 里堆选区分支:它已经 1416 行,`editor.css` 1340 行且后半段是补丁叠加,继续堆会很快失控。
|
||||
建议路径:**先重做地基与 UI(P0)→ 上选区(P1)→ 修裁剪/画布(P2)→ 图层增强(P3)→ 输出工作流(P4)**。
|
||||
不要直接往现有 `events.js` 里堆选区分支:它已经 1416 行,`e `40 行且后半段是补丁叠加,继续堆会很快失控。
|
||||
|
||||
> 便利性不改变架构判断,反而强化了 P0 的必要性:高频动作要「就地、一步可达」,靠的是命令层与统一状态机,而不是往菜单里加更多条目。
|
||||
|
||||
@@ -37,56 +37,56 @@
|
||||
打开图片 → 框选/抠出局部 → 图层化编辑 → 裁剪 / 改尺寸 → 按规范导出 → 回写节点
|
||||
```
|
||||
|
||||
典型场景:截图里圈出商品 → 复制成独立层 → 擦掉多余部分 → 裁成 800×800 → 导出当前这一张。
|
||||
典型场景:截图里圈出商品 → 复制成独立层 → 擦掉多余部分 → 裁成 800×800 → 导出当前这一张。
|
||||
**一次会话只处理一张图,输出一次只产出一个结果**;不引入队列、批量选择、批量命名、批量下载等概念。
|
||||
|
||||
### 1.2 明确不做(边界)
|
||||
|
||||
| 不做 | 原因 |
|
||||
| --- | --- |
|
||||
| **批量出图 / 多图队列 / 批量导出 / 批量改名** | 用户明确排除;单张处理即可,避免把编辑器做成队列面板 |
|
||||
| 调色:曲线 / 色阶 / HSL / 色彩平衡 / 色相饱和度 | 用户明确排除;牵涉色彩管理与 LUT,收益低 |
|
||||
| 滤镜 / 模糊 / 锐化 / 降噪(作为调色类功能) | 同上;**羽化**作为选区属性保留 |
|
||||
| CMYK / 16bit / RAW / ICC / 印刷输出 | 浏览器 Canvas 2D 只有 8bit sRGB |
|
||||
| 智能对象 / 动作 / 脚本 / 通道 / 路径面板 | 复杂度远超「简化版」 |
|
||||
| AI 抠图 | 已有外部链路(`xianyi-cutout` / 本地 rembg),插件只负责后期修图 |
|
||||
| 非破坏性蒙版式调色图层 | 一期不需要;P3 只做「图层蒙版」这一项 |
|
||||
| 完整菜单栏(文件/编辑/图像/图层/选择/视图…) | 与「便利」冲突;低频命令收进一个「更多」下拉 |
|
||||
| 不做 | 原因 |
|
||||
| ------------------------------- | -------------------------------------------- |
|
||||
| **批量出图 / 多图队列 / 批量导出 / 批量改名** | 用户明确排除;单张处理即可,避免把编辑器做成队列面板 |
|
||||
| 调色:曲线 / 色阶 / HSL / 色彩平衡 / 色相饱和度 | 用户明确排除;牵涉色彩管理与 LUT,收益低 |
|
||||
| 滤镜 / 模糊 / 锐化 / 降噪(作为调色类功能) | 同上;**羽化**作为选区属性保留 |
|
||||
| CMYK / 16bit / RAW / ICC / 印刷输出 | 浏览器 Canvas 2D 只有 8bit sRGB |
|
||||
| 智能对象 / 动作 / 脚本 / 通道 / 路径面板 | 复杂度远超「简化版」 |
|
||||
| AI 抠图 | 已有外部链路(`xianyi-cutout` / 本地 rembg),插件只负责后期修图 |
|
||||
| 非破坏性蒙版式调色图层 | 一期不需要;P3 只做「图层蒙版」这一项 |
|
||||
| 完整菜单栏(文件/编辑/图像/图层/选择/视图…) | 与「便利」冲突;低频命令收进一个「更多」下拉 |
|
||||
|
||||
### 1.3 与 PS 的能力对照
|
||||
|
||||
| PS 能力 | 简化版取舍 |
|
||||
| --- | --- |
|
||||
| 选框 / 套索 / 魔棒 | ✅ 矩形、椭圆、多边形、自由套索;魔棒放二期 |
|
||||
| 选区变换 / 加减 / 反选 / 羽化 | ✅ 一期全做(羽化用 Canvas filter) |
|
||||
| 复制 / 剪切到新图层、清除、填充、描边 | ✅ 核心,且做成选区旁的浮动操作条 |
|
||||
| 图层 / 显隐 / 锁定 / 不透明度 / 排序 | ✅ 已有 |
|
||||
| 混合模式 / 图层蒙版 / 编组 / 缩略图 | 🟡 P3 补 |
|
||||
| 裁剪 / 画布大小 / 图像大小 / 旋转翻转 | 🟡 P2 补,且改为可撤销 |
|
||||
| 自由变换(Ctrl+T) | 🟡 已有选中对象的移动/缩放/旋转,P2 扩展到选区内容 |
|
||||
| 画笔 / 橡皮 / 文字 / 形状 / 吸管 / 抓手 | ✅ 已有,不重写 |
|
||||
| 历史面板 / 多步撤销 | ✅ 已有栈,P0 补标签与面板 |
|
||||
| 导出 / 存储为 Web 所用格式 | 🟡 P4,单张可配置预设 |
|
||||
| 菜单栏 / 批量处理 / 滤镜 / 调色 / 3D / 印刷 | ❌ 不做 |
|
||||
| PS 能力 | 简化版取舍 |
|
||||
| ------------------------------ | ----------------------------- |
|
||||
| 选框 / 套索 / 魔棒 | ✅ 矩形、椭圆、多边形、自由套索;魔棒放二期 |
|
||||
| 选区变换 / 加减 / 反选 / 羽化 | ✅ 一期全做(羽化用 Canvas filter) |
|
||||
| 复制 / 剪切到新图层、清除、填充、描边 | ✅ 核心,且做成选区旁的浮动操作条 |
|
||||
| 图层 / 显隐 / 锁定 / 不透明度 / 排序 | ✅ 已有 |
|
||||
| 混合模式 / 图层蒙版 / 编组 / 缩略图 | 🟡 P3 补 |
|
||||
| 裁剪 / 画布大小 / 图像大小 / 旋转翻转 | 🟡 P2 补,且改为可撤销 |
|
||||
| 自由变换(Ctrl+T) | 🟡 已有选中对象的移动/缩放/旋转,P2 扩展到选区内容 |
|
||||
| 画笔 / 橡皮 / 文字 / 形状 / 吸管 / 抓手 | ✅ 已有,不重写 |
|
||||
| 历史面板 / 多步撤销 | ✅ 已有栈,P0 补标签与面板 |
|
||||
| 导出 / 存储为 Web 所用格式 | 🟡 P4,单张可配置预设 |
|
||||
| 菜单栏 / 批量处理 / 滤镜 / 调色 / 3D / 印刷 | ❌ 不做 |
|
||||
|
||||
---
|
||||
|
||||
## 2. 现状盘点(代码级)
|
||||
|
||||
| 能力 | 实现位置 | 关键事实 |
|
||||
| --- | --- | --- |
|
||||
| 11 个工具 | `editor/dom.js` 工具栏 + `editor/events.js` 分发 | select / brush / eraser / pen / text / rect / circle / arrow / picker / hand / crop |
|
||||
| 位图图层 | `editor/viewport.js#setupCanvas` | 初始 `base`(locked, z=0) + `draw`(z=1);**每个图层都是 imgW×imgH 全幅 canvas** |
|
||||
| 矢量对象 | `editor/objects.js` `layerUnits()` | 文字/形状/钢笔按 z 与位图混排,1.0.5 已统一为唯一真源 |
|
||||
| 图层面板 | `editor/layers.js#renderLayerPanel` | 显隐 / 锁定 / 删除 / 颜色 / 线宽 / 透明度 / 拖拽排序 / 4 个排序按钮;**无缩略图、无混合模式、无编组、无多选** |
|
||||
| 历史 | `editor/history.js` | `snapshotState()` 像素快照;50 条 + 32–128MB 双预算;`restorePath()` 决定哪些层跳过像素 |
|
||||
| 裁剪 | `editor/crop.js#confirmCrop` | `getCompositeCanvas()` → flatten → `setupCanvas(cropC)` 重建所有层 → 改 `S.imgW/imgH` → **`S.history=[]`**;比例/尺寸约束;越界部分透明 |
|
||||
| 图片放置 | `editor/placement.js` | 粘贴/导入先进入放置模式(移动/8 手柄/旋转),**必须 Enter 或点击外部确认才落层** |
|
||||
| 剪贴板 | `editor/events.js#onPaste` | document 捕获阶段,命中图片即 `stopImmediatePropagation()`(防宿主 window 抢粘贴) |
|
||||
| 视图 | `editor/viewport.js` | zoom 0.1–10、自由平移、`overlayPad` 交互外扩、`getPos()` 统一坐标换算 |
|
||||
| 输出 | `editor/index.js#exportResult` | 固定 PNG `toBlob` → `glue.js` 转 dataURL → `setNodeImage` / `createImageNode` |
|
||||
| 内存 | `editor/index.js#releaseEditorMemory` | `close()` 释放所有像素、原图、历史;**会话状态不保留** |
|
||||
| 宿主 | `plugin/glue.js` | 只对 `ref` 节点暴露;`ctx.canvas.*`;`ctx.storage` 是宿主提供的小 KV(localStorage),**不是像素仓库** |
|
||||
| 能力 | 实现位置 | 关键事实 |
|
||||
| ------ | ------------------------------------------- | ------------------------------------------------------------------------------------------------------------------- |
|
||||
| 11 个工具 | `editor/dom.js` 工具栏 + `editor/events.js` 分发 | select / brush / eraser / pen / text / rect / circle / arrow / picker / hand / crop |
|
||||
| 位图图层 | `editor/viewport.js#setupCanvas` | 初始 `base`(locked, z=0) + `draw`(z=1);**每个图层都是 imgW×imgH 全幅 canvas** |
|
||||
| 矢量对象 | `editor/objects.js` `layerUnits()` | 文字/形状/钢笔按 z 与位图混排,1.0.5 已统一为唯一真源 |
|
||||
| 图层面板 | `editor/layers.js#renderLayerPanel` | 显隐 / 锁定 / 删除 / 颜色 / 线宽 / 透明度 / 拖拽排序 / 4 个排序按钮;**无缩略图、无混合模式、无编组、无多选** |
|
||||
| 历史 | `editor/history.js` | `snapshotState()` 像素快照;50 条 + 32–128MB 双预算;`restorePath()` 决定哪些层跳过像素 |
|
||||
| 裁剪 | `editor/crop.js#confirmCrop` | `getCompositeCanvas()` → flatten → `setupCanvas(cropC)` 重建所有层 → 改 `S.imgW/imgH` → **`S.history=[]`**;比例/尺寸约束;越界部分透明 |
|
||||
| 图片放置 | `editor/placement.js` | 粘贴/导入先进入放置模式(移动/8 手柄/旋转),**必须 Enter 或点击外部确认才落层** |
|
||||
| 剪贴板 | `editor/events.js#onPaste` | document 捕获阶段,命中图片即 `stopImmediatePropagation()`(防宿主 window 抢粘贴) |
|
||||
| 视图 | `editor/viewport.js` | zoom 0.1–10、自由平移、`overlayPad` 交互外扩、`getPos()` 统一坐标换算 |
|
||||
| 输出 | `editor/index.js#exportResult` | 固定 PNG `toBlob` → `glue.js` 转 dataURL → `setNodeImage` / `createImageNode` |
|
||||
| 内存 | `editor/index.js#releaseEditorMemory` | `close()` 释放所有像素、原图、历史;**会话状态不保留** |
|
||||
| 宿主 | `plugin/glue.js` | 只对 `ref` 节点暴露;`ctx.canvas.*`;`ctx.storage` 是宿主提供的小 KV(localStorage),**不是像素仓库** |
|
||||
|
||||
---
|
||||
|
||||
@@ -96,61 +96,61 @@
|
||||
|
||||
### 3.1 选区(当前完全没有)
|
||||
|
||||
| 缺口 | 影响 | 优先级 |
|
||||
| --- | --- | --- |
|
||||
| 无矩形/椭圆/多边形/套索选区 | 无法「抠出局部」「只擦一块」 | P1 |
|
||||
| 无蚂蚁线、无加减选、无反选/全选/取消 | 选区不可见、不可调整 | P1 |
|
||||
| 无羽化 | 边缘生硬,合成痕迹明显 | P1 |
|
||||
| 无复制/剪切到新层、Delete 清除、填充/描边 | 选区没有落点,等于没用 | P1 |
|
||||
| 选区不能约束画笔/橡皮 | 精细化修图做不到 | P1(可后置) |
|
||||
| 魔棒 / 色彩范围 | 纯色背景一键去背 | P2+(worker 受限,见 §7) |
|
||||
| 缺口 | 影响 | 优先级 |
|
||||
| ------------------------- | -------------- | ------------------- |
|
||||
| 无矩形/椭圆/多边形/套索选区 | 无法「抠出局部」「只擦一块」 | P1 |
|
||||
| 无蚂蚁线、无加减选、无反选/全选/取消 | 选区不可见、不可调整 | P1 |
|
||||
| 无羽化 | 边缘生硬,合成痕迹明显 | P1 |
|
||||
| 无复制/剪切到新层、Delete 清除、填充/描边 | 选区没有落点,等于没用 | P1 |
|
||||
| 选区不能约束画笔/橡皮 | 精细化修图做不到 | P1(可后置) |
|
||||
| 魔棒 / 色彩范围 | 纯色背景一键去背 | P2+(worker 受限,见 §7) |
|
||||
|
||||
### 3.2 非破坏性与裁剪(当前是最大架构债)
|
||||
|
||||
| 缺口 | 具体表现 | 优先级 |
|
||||
| --- | --- | --- |
|
||||
| 裁剪即 flatten | `confirmCrop()` 合成所有可见层 → 重建 `base`/`draw`,图层结构全部丢失 | P2 |
|
||||
| 裁剪不可撤销 | `S.history = []; S.redoStack = []` | P2 |
|
||||
| 裁剪丢变换信息 | 只对 `textLayers`/`shapeLayers` 映射 x/y/lw/fontSize,**没处理 `rotation`** | P2 |
|
||||
| 无「画布大小」/「图像大小」 | 只能靠裁剪栏的「尺寸约束」间接缩放 | P2 |
|
||||
| 无 90° 旋转 / 水平垂直翻转 / 拉直 | 基础图像操作缺失 | P2 |
|
||||
| 全幅画布模型 | 每个图层都被钉死在 imgW×imgH,裁剪必须重画所有层 | P0 设计 / P2 实施 |
|
||||
| 缺口 | 具体表现 | 优先级 |
|
||||
| ---------------------- | ------------------------------------------------------------------- | ------------- |
|
||||
| 裁剪即 flatten | `confirmCrop()` 合成所有可见层 → 重建 `base`/`draw`,图层结构全部丢失 | P2 |
|
||||
| 裁剪不可撤销 | `S.history = []; S.redoStack = []` | P2 |
|
||||
| 裁剪丢变换信息 | 只对 `textLayers`/`shapeLayers` 映射 x/y/lw/fontSize,**没处理 `rotation`** | P2 |
|
||||
| 无「画布大小」/「图像大小」 | 只能靠裁剪栏的「尺寸约束」间接缩放 | P2 |
|
||||
| 无 90° 旋转 / 水平垂直翻转 / 拉直 | 基础图像操作缺失 | P2 |
|
||||
| 全幅画布模型 | 每个图层都被钉死在 imgW×imgH,裁剪必须重画所有层 | P0 设计 / P2 实施 |
|
||||
|
||||
### 3.3 图层
|
||||
|
||||
| 缺口 | 说明 | 优先级 |
|
||||
| --- | --- | --- |
|
||||
| 无缩略图 | 图层多了分不清哪张是哪张 | P3 |
|
||||
| 无混合模式 | 正片叠底/滤色/叠加是合成常用 | P3 |
|
||||
| 无图层蒙版 | 抠图只能破坏性擦除,不能反悔 | P3 |
|
||||
| 无重命名 / 多选 / 编组 | 复杂图难管理 | P3 |
|
||||
| 缺口 | 说明 | 优先级 |
|
||||
| ------------------ | ----------------------------------------------------------------------------------------------- | ---------- |
|
||||
| 无缩略图 | 图层多了分不清哪张是哪张 | P3 |
|
||||
| 无混合模式 | 正片叠底/滤色/叠加是合成常用 | P3 |
|
||||
| 无图层蒙版 | 抠图只能破坏性擦除,不能反悔 | P3 |
|
||||
| 无重命名 / 多选 / 编组 | 复杂图难管理 | P3 |
|
||||
| `resetDraw()` 语义歧义 | 「清空标注」只清非 base 层像素,留下空白粘贴层(1.0.5 遗留)⇒ **已裁定改为「全部还原」**:删所有非 base 层 + 清绘制 + 复位变换,一步可撤销;按钮改名「还原原图」 | P0 定语义(已定) |
|
||||
|
||||
### 3.4 输出(单张)
|
||||
|
||||
| 缺口 | 说明 | 优先级 |
|
||||
| --- | --- | --- |
|
||||
| 只有 PNG | 无 JPG/WebP、无质量控制 | P4 |
|
||||
| 无背景切换(透明 / 白底) | 电商出图要手工来回切换 | P4 |
|
||||
| 无体积上限策略 | 无法保证 ≤500KB 这类交付规范 ⇒ **已裁定做成可切换预设**(800×800 / 长边 640 / 质量迭代 ≤500KB,存 `ctx.settings`) | P4(随 P1 带上) |
|
||||
| 无下载 / 复制到系统剪贴板 | 只能回写宿主节点 | P4 |
|
||||
| 导出步骤偏多 | 覆盖 / 新建 / 退出三个按钮分散,没有「记住上次选择」 | P0 / P4 |
|
||||
| 导出后图层信息丢失 | 节点里是一张扁平 PNG,下次打开要从头来 | P5(需宿主配合) |
|
||||
| 缺口 | 说明 | 优先级 |
|
||||
| -------------- | ------------------------------------------------------------------------------------ | ----------- |
|
||||
| 只有 PNG | 无 JPG/WebP、无质量控制 | P4 |
|
||||
| 无背景切换(透明 / 白底) | 电商出图要手工来回切换 | P4 |
|
||||
| 无体积上限策略 | 无法保证 ≤500KB 这类交付规范 ⇒ **已裁定做成可切换预设**(800×800 / 长边 640 / 质量迭代 ≤500KB,存 `ctx.settings`) | P4(随 P1 带上) |
|
||||
| 无下载 / 复制到系统剪贴板 | 只能回写宿主节点 | P4 |
|
||||
| 导出步骤偏多 | 覆盖 / 新建 / 退出三个按钮分散,没有「记住上次选择」 | P0 / P4 |
|
||||
| 导出后图层信息丢失 | 节点里是一张扁平 PNG,下次打开要从头来 | P5(需宿主配合) |
|
||||
|
||||
### 3.5 交互、快捷键、状态
|
||||
|
||||
| 缺口 | 说明 | 优先级 |
|
||||
| --- | --- | --- |
|
||||
| 快捷键是数字 1–0 | 无 PS 习惯的 V/B/E/M/L/C、Ctrl+A/C/X/V/J/D/T/Z | P0 映射层 / P5 全量 |
|
||||
| `Ctrl+V` 已被占用 | 现在恒定「贴为新图层」,与「粘贴选区内容」语义冲突,需明确规则 | P1 |
|
||||
| Delete 只删文字/形状 | 位图层内容不能一键清除 | P1 |
|
||||
| 无右键菜单 / 无工具选项栏 / 无状态栏 | 参数散落、当前状态不可见 | P0 |
|
||||
| 错误提示用 `window.alert` | `pasteImageFromUrl` 失败直接弹窗,无 toast | P0 |
|
||||
| 图片放置要二次确认 | 拖完还得按 Enter,多一步 | P0(便利性) |
|
||||
| overlay 单 canvas 多用 | 裁剪遮罩、选中框、笔刷环、放置预览、提示文字全在 `S.overlayCanvas`,共用 `clearOverlay()`;**加蚂蚁线必然互相擦除** | P0 |
|
||||
| `editor.css` 补丁堆积 | 1340 行,后半段大量 `!important`;工具栏 `position:absolute; top:68px`,撤销按钮 `right:154px` 等魔数;`.iwb-editor-footer` 空且 `display:none`;`.iwb-editor-zoom-hint` 绝对定位 | P0 |
|
||||
| 无响应式 / 无亮色主题 | 窄窗口下 290px 图层面板 + 44px 工具栏挤压画布 | P5 |
|
||||
| 关闭即清空 | 无草稿、无二次编辑;`ctx.storage` 只是 localStorage 小 KV | P5 |
|
||||
| 缺口 | 说明 | 优先级 |
|
||||
| --------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------ | -------------- |
|
||||
| 快捷键是数字 1–0 | 无 PS 习惯的 V/B/E/M/L/C、Ctrl+A/C/X/V/J/D/T/Z | P0 映射层 / P5 全量 |
|
||||
| `Ctrl+V` 已被占用 | 现在恒定「贴为新图层」,与「粘贴选区内容」语义冲突,需明确规则 | P1 |
|
||||
| Delete 只删文字/形状 | 位图层内容不能一键清除 | P1 |
|
||||
| 无右键菜单 / 无工具选项栏 / 无状态栏 | 参数散落、当前状态不可见 | P0 |
|
||||
| 错误提示用 `window.alert` | `pasteImageFromUrl` 失败直接弹窗,无 toast | P0 |
|
||||
| 图片放置要二次确认 | 拖完还得按 Enter,多一步 | P0(便利性) |
|
||||
| overlay 单 canvas 多用 | 裁剪遮罩、选中框、笔刷环、放置预览、提示文字全在 `S.overlayCanvas`,共用 `clearOverlay()`;**加蚂蚁线必然互相擦除** | P0 |
|
||||
| `editor.css` 补丁堆积 | 1340 行,后半段大量 `!important`;工具栏 `position:absolute; top:68px`,撤销按钮 `right:154px` 等魔数;`.iwb-editor-footer` 空且 `display:none`;`.iwb-editor-zoom-hint` 绝对定位 | P0 |
|
||||
| 无响应式 / 无亮色主题 | 窄窗口下 290px 图层面板 + 44px 工具栏挤压画布 | P5 |
|
||||
| 关闭即清空 | 无草稿、无二次编辑;`ctx.storage` 只是 localStorage 小 KV | P5 |
|
||||
|
||||
---
|
||||
|
||||
@@ -187,18 +187,18 @@
|
||||
|
||||
### 4.1 便利性准则(验收口径)
|
||||
|
||||
| 准则 | 具体做法 | 反例(不做) |
|
||||
| --- | --- | --- |
|
||||
| 高频动作 0 层级 | 选区操作浮动条、输出按钮常驻顶栏、图层显隐/锁定就地点击 | 先开菜单 → 子菜单 → 对话框 |
|
||||
| 低频动作 1 层级 | 「更多 ▾」一次展开,展开后可常驻 | 二级子菜单、向导式多步 |
|
||||
| 少确认 | 粘贴/导入图片拖完即落层(提供 Esc 撤销,取消 Enter 确认);裁剪确认保留一次(破坏性较大) | 每个操作都弹「确定吗」 |
|
||||
| 撤销可兜底 | 任何一步都能 Ctrl+Z 回退,包括裁剪与选区清除 | 清空历史、不可撤销的破坏性操作 |
|
||||
| 状态可见 | 状态栏常驻尺寸/坐标/选区/当前层;toast 取代 `window.alert` | 只在 console 报错、浮层提示一闪而过 |
|
||||
| 记住选择 | 上次输出格式、背景、尺寸预设、面板开合存 `ctx.settings` | 每次打开都回到默认值 |
|
||||
| 就地编辑 | 尺寸、比例、羽化直接输入数字;选区可拖动、8 手柄调整、实时显示 W×H | 打开属性面板改参数 |
|
||||
| 三种入口并存 | 浮动条 / 右键菜单 / 快捷键,任一都会走同一 `execute()` | 三条路径各实现一遍 |
|
||||
| 画布优先 | 面板默认 260px 且可收起;工具栏 40px;窄窗口自动收面板 | 固定 290px 面板 + 常驻色板挤压画布 |
|
||||
| 无队列 | 一次一张、一次一个结果;不做批量勾选、批量命名、批量下载 | 输出队列、任务进度条、批量结果列表 |
|
||||
| 准则 | 具体做法 | 反例(不做) |
|
||||
| --------- | --------------------------------------------------- | ---------------------- |
|
||||
| 高频动作 0 层级 | 选区操作浮动条、输出按钮常驻顶栏、图层显隐/锁定就地点击 | 先开菜单 → 子菜单 → 对话框 |
|
||||
| 低频动作 1 层级 | 「更多 ▾」一次展开,展开后可常驻 | 二级子菜单、向导式多步 |
|
||||
| 少确认 | 粘贴/导入图片拖完即落层(提供 Esc 撤销,取消 Enter 确认);裁剪确认保留一次(破坏性较大) | 每个操作都弹「确定吗」 |
|
||||
| 撤销可兜底 | 任何一步都能 Ctrl+Z 回退,包括裁剪与选区清除 | 清空历史、不可撤销的破坏性操作 |
|
||||
| 状态可见 | 状态栏常驻尺寸/坐标/选区/当前层;toast 取代 `window.alert` | 只在 console 报错、浮层提示一闪而过 |
|
||||
| 记住选择 | 上次输出格式、背景、尺寸预设、面板开合存 `ctx.settings` | 每次打开都回到默认值 |
|
||||
| 就地编辑 | 尺寸、比例、羽化直接输入数字;选区可拖动、8 手柄调整、实时显示 W×H | 打开属性面板改参数 |
|
||||
| 三种入口并存 | 浮动条 / 右键菜单 / 快捷键,任一都会走同一 `execute()` | 三条路径各实现一遍 |
|
||||
| 画布优先 | 面板默认 260px 且可收起;工具栏 40px;窄窗口自动收面板 | 固定 290px 面板 + 常驻色板挤压画布 |
|
||||
| 无队列 | 一次一张、一次一个结果;不做批量勾选、批量命名、批量下载 | 输出队列、任务进度条、批量结果列表 |
|
||||
|
||||
> 「便利」的实现依赖 P0 的命令层:浮动条、右键菜单、快捷键只是三个**视图**,背后必须是同一条 `execute(label, mutator)`,否则便利会变成三套逻辑各修一遍。
|
||||
|
||||
@@ -249,16 +249,17 @@ S.selection = {
|
||||
|
||||
在 `.iwb-editor-canvas-stack` 内拆成三个独立 canvas,各管各的 `clear()`:
|
||||
|
||||
| 层 | 内容 |
|
||||
| --- | --- |
|
||||
| `interactionCanvas` | 选中框、8 手柄、旋转弧、放置预览、裁剪遮罩 |
|
||||
| `selectionCanvas` | 蚂蚁线(rAF 驱动 `lineDashOffset`)、选区外暗化 |
|
||||
| `cursorCanvas` | 笔刷环、吸管提示光标 |
|
||||
| 层 | 内容 |
|
||||
| ------------------- | ---------------------------------- |
|
||||
| `interactionCanvas` | 选中框、8 手柄、旋转弧、放置预览、裁剪遮罩 |
|
||||
| `selectionCanvas` | 蚂蚁线(rAF 驱动 `lineDashOffset`)、选区外暗化 |
|
||||
| `cursorCanvas` | 笔刷环、吸管提示光标 |
|
||||
|
||||
现在 `clearOverlay()` 一擦全擦,加蚂蚁线后必然与裁剪框/选中框互相打架,必须先拆。浮动操作条是 **DOM 元素**(不是画在 canvas 上),便于点击、键盘可达与本地化。
|
||||
|
||||
### 5.5 非破坏性文档模型(P2 的选型)
|
||||
|
||||
|
||||
现有模型是「每个图层 = 全幅 imgW×imgH 画布」,画布尺寸就是图片尺寸,所以裁剪只能重画所有层。两条路线:
|
||||
|
||||
| 路线 | 做法 | 改动面 | 结论 |
|
||||
|
||||
+46
-51
@@ -1,81 +1,76 @@
|
||||
# 位图转矢量(image-vectorize)
|
||||
|
||||
> ## ⛔ 已下线,未发布(2026-11-05)
|
||||
>
|
||||
> 这个插件**已经从线上清单移除、KV 字节已删、宿主的 `wasm-unsafe-eval` 也已收回**。
|
||||
> 原因:描摹质量达不到可交付线 —— 中文笔画断裂、抗锯齿边缘起毛刺、浅色块碎层,
|
||||
> 「看着变矢量但没法用」。引擎参数已调到合理区间(曲线迭代 2 / 颜色精度夹 1–5 /
|
||||
> 降采样去毛刺 / SVG 层删背景),剩下的是**算法定位**问题:VTracer 适合 logo、线稿、
|
||||
> 纯平色块,不适合照片和带抗锯齿的合成图。
|
||||
>
|
||||
> **本目录仅作存档**(代码已验证可用,不要按下面的命令直接发布)。真要复活,
|
||||
> 需要同时恢复三处:① 宿主 `_headers` 的 `'wasm-unsafe-eval'` ② KV 清单条目
|
||||
> ③ 插件管理里勾选启用。删掉本目录也不影响线上任何东西。
|
||||
把节点的位图描摹成矢量,输出 SVG 或 PNG 节点。引擎是 **potrace**(Peter Selinger 的二值轮廓算法,
|
||||
这里用它的 JS 移植 `[email protected]`,GPL-2.0)—— 和 Inkscape「位图转矢量」同一个内核。
|
||||
|
||||
把节点的位图描摹成矢量,输出 SVG 或透明底 PNG 节点。引擎是 [VTracer](https://github.com/visioncortex/vtracer)
|
||||
(Rust → WebAssembly,MIT),Inkscape「位图转矢量」的现代替代品:它是原生彩色分层,不像 Inkscape
|
||||
那样把多次 potrace 结果叠起来(色块交界处常有白缝)。
|
||||
## 为什么换了引擎(v0.1 → v0.2,2026-11-05)
|
||||
|
||||
## 必须先满足的宿主条件
|
||||
v0.1 用 VTracer(彩色分层 + 样条拟合,wasm)。实测在文字图上:**中文笔画断裂、抗锯齿边缘起毛刺、
|
||||
浅色块碎成多层** —— 用户的原话是「看着变矢量了但没法用」,当天就下线了。
|
||||
|
||||
宿主 CSP 的 `script-src` 必须包含 **`'wasm-unsafe-eval'`**,否则 wasm 无法编译、插件完全不可用
|
||||
(浏览器报 `Compiling or instantiating WebAssembly module violates ...`)。这一项只放行 wasm 编译,
|
||||
**不**放行字符串 `eval` / `new Function`,因此不等于放宽脚本执行。
|
||||
v0.2 换 potrace,并且按用户要求**只做单色 / 灰度**(不做彩色):
|
||||
|
||||
宿主仓对应改动:`_headers` → `script-src 'self' 'wasm-unsafe-eval'`。
|
||||
| 维度 | VTracer(v0.1) | potrace(v0.2) |
|
||||
|---|---|---|
|
||||
| 文字保形 | 笔画会断 | 笔画完整(二值轮廓追踪不猜颜色) |
|
||||
| 毛刺 | 参数调不掉,得先降采样模糊 | `turdSize` 直接吃掉小于 N 像素的碎片 |
|
||||
| 颜色 | 彩色分层(也是碎层根源) | 单色 / 灰度 N 层,层数可控 2–5 |
|
||||
| 依赖 | wasm ⇒ 要放宽 CSP `'wasm-unsafe-eval'` | **纯 JS ⇒ 不动 CSP** |
|
||||
| 体积 | 238KB(wasm base64 内联) | **116KB** |
|
||||
|
||||
## 功能
|
||||
|
||||
- 五个预设:标志/图标、插画/卡通、照片、线稿/黑白、**边缘净化**
|
||||
- 参数:颜色模式(彩色/黑白)、分层方式(堆叠/镂空)、曲线(样条/多边形)、颜色精度、
|
||||
背景(去除/保留)、边缘净化强度(原尺寸 / 1÷2 / 1÷3 / 1÷4)、输出倍率(1–4× 超采样)
|
||||
- 高级参数:色层差异、噪点过滤、拐角阈值、路径简化、曲线迭代
|
||||
- 预览:按住空格对比原图;面板底部显示路径数 / 颜色数 / 体积 / 耗时
|
||||
- 输出:**保存为节点**(透明底 PNG,按输出倍率超采样)· **下载 SVG**(真矢量文件)
|
||||
- 三个预设:文字 / 线稿(单色)、菜单 / 图文(灰度 3 层)、抠图轮廓(单色 + 强去毛刺)
|
||||
- 描摹方式:**灰度分层**(层数 2–5)/ **纯单色**
|
||||
- 高频参数只有两个滑杆:**去小点**(turdSize)、**边缘**(硬朗 / 标准 / 圆润 → alphaMax)
|
||||
- 高级:阈值(自动 / 手动)、反相(黑底白字用负片)、单色填充色
|
||||
- 预览:按住空格对比原图;面板显示路径数 / 层数 / 体积 / 耗时
|
||||
- 输出:**保存为节点**(PNG,按输出倍率 1–4× 用矢量重绘)· **下载 SVG**(真矢量)
|
||||
|
||||
## 引擎的三个实测坑(改代码前必读)
|
||||
## 灰度分层为什么自己算阈值
|
||||
|
||||
这三条都是 2026-11-05 在 Chromium 里扫参数扫出来的,写死在 `plugin/engine.js`:
|
||||
上游 `Posterizer` 的 `steps` 传数字时会跑**直方图多级阈值搜索**,`steps: 5` 实测 **28 秒**(指数级),
|
||||
不可用。这里改成自己算**等像素量分位**再以数组形式传进去(O(pixels)),5 层也只要几十毫秒。
|
||||
|
||||
1. **`colorPrecision` 语义与官方 CLI 相反**。wasm 侧直接把它当「颜色相似度阈值」,值越大越容易
|
||||
把不同颜色并成一团:≥6 时整张图塌成一个色块,=8 直接 wasm abort。滑杆因此夹在 1–5。
|
||||
2. **`maxIterations` ≥3 会过拟合抗锯齿边缘**。一个正圆会被拉成水滴形、圆角矩形的角会被吃掉。
|
||||
默认 2 是实测最稳的值。
|
||||
3. **abort 后实例不可复用**。`__wbg_init` 见到已有实例会直接返回坏的那个,所以 `engine.js` 在
|
||||
catch 里显式 `__reset_wasm()` 再重建(`plugin/vendor/vtracer.js` 的本地改动就是为了这个钩子)。
|
||||
两个必须处理的细节(`engine.js#quantileThresholds`,实测踩过):
|
||||
|
||||
另外:**不要**给引擎喂带 alpha 的图。把背景改成透明会触发它的 color keying,透明区被填成 key
|
||||
color 后与图中相近颜色混淆 —— 实测红圆变形、中文笔画塌成黑块。背景处理放在描摹之后、SVG 层面删
|
||||
背景 path(`trace.js#stripBackgroundLayer`)。
|
||||
1. **主背景色要排除在人口统计之外**。菜单图底色常占 60–80% 像素,不排除的话切点全落在背景里,
|
||||
文字和背景还是分不开(等于白分层)。
|
||||
2. **切点必须严格递增**。背景是巨大尖峰,多个切点会算出同一个亮度值 —— 去重后层数变少,
|
||||
Posterizer 还会算出 0 透明度让整层消失。
|
||||
|
||||
## 毛边净化为什么要降采样
|
||||
## 许可
|
||||
|
||||
rembg 那种 ±3px 的毛边,调 `lengthThreshold` / `cornerThreshold` 是抹不掉的 —— 引擎会忠实保留
|
||||
每个像素抖动。先把图降到 1÷2~1÷4(双线性插值天然把毛刺平均掉)再描摹,轮廓才真正变光滑。
|
||||
代价是小字会糊,所以做成可选强度,默认原尺寸。
|
||||
potrace 与其 JS 移植都是 **GPL-2.0**(见 `plugin/vendor/potrace/LICENSE`)。当前用途是**自己用、
|
||||
不商用**:GPL 的义务由「分发」触发,自用不触发;且本插件产物是**未混淆的单文件可读源码**
|
||||
(`src/index.js` 既是产物也是源码),即使哪天对外提供,源码是随附的。
|
||||
若将来要商用/闭源分发,换 MIT 的等价实现,或按 GPL 开源该插件。
|
||||
|
||||
## 开发
|
||||
|
||||
```bash
|
||||
npm run build -- image-vectorize # plugin/ → src/index.js(esbuild IIFE,wasm base64 内联)
|
||||
npm run validate # 契约校验
|
||||
node image-vectorize/tools/harness.mjs # 本地端到端(合成宿主 + 真 Chromium)
|
||||
node image-vectorize/tools/e2e-site.mjs # 真站(CSP / SRI / 真实 KV)
|
||||
```
|
||||
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/e2e-site.mjs # 真站(KV / SRI / CSP / 真实画布桥)
|
||||
|
||||
wasm 以 base64 内联在 `plugin/vendor/wasm-b64.js`,因为宿主发布链路只接受单个 `.js`。
|
||||
换 wasm 版本时同时更新 `plugin/vendor/vtracer.{js,wasm}` 并重新生成该文件。
|
||||
# 拿真实素材调参数(不进 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
|
||||
# → 产物 SVG + 一张「原图 / 结果」对比图(~-/tmp/vz-cli/)
|
||||
```
|
||||
|
||||
发布:
|
||||
|
||||
```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.1.1 --upload
|
||||
--version image-vectorize=0.2.0 --upload
|
||||
```
|
||||
|
||||
## 已知限制
|
||||
|
||||
- 小字号(<40px)文字描摹后会变形,这是矢量化本身的局限,建议改用「线稿/黑白」或降一级颜色精度
|
||||
- 照片类素材色层多、SVG 体积大(几百 KB 到数 MB),必要时用「照片」预设把色层差异调大
|
||||
- 超过 2000px 的图会自动降到 2000px 描摹(避免主线程卡死),输出仍按原尺寸渲染
|
||||
- **照片不适合**:potrace 只懂明暗,照片会被压成几块灰阶(这不是 bug,是算法定位)
|
||||
- 小字号(<24px)文字描摹后仍会变形;灰度模式可缓解(把浅色笔画留在单独一层)
|
||||
- 超过 2000px 的图自动降到 2000px 再描摹(纯 JS 单线程,避免卡主线程)
|
||||
- 灰度模式的「灰」是 `fill-opacity` 叠出来的(不是多条不同色 path),所以 SVG 里只有一种 fill 色
|
||||
@@ -1,8 +1,8 @@
|
||||
{
|
||||
"name": "@iwb-plugin/image-vectorize",
|
||||
"private": true,
|
||||
"version": "0.1.1",
|
||||
"description": "位图转矢量:VTracer(Rust/WebAssembly)描摹,彩色分层或黑白二值,输出 SVG 与透明 PNG 节点;内置「边缘净化」用于清理抠图毛边",
|
||||
"version": "0.2.0",
|
||||
"description": "位图转矢量:potrace(纯 JS)单色/灰度描摹,输出 SVG 与 PNG 节点;对文字、logo、线稿保形好,不需要 wasm",
|
||||
"ibwPlugin": {
|
||||
"id": "image-vectorize",
|
||||
"entry": "src/index.js",
|
||||
|
||||
@@ -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 }
|
||||
}
|
||||
@@ -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
@@ -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 }
|
||||
}
|
||||
@@ -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
@@ -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)
|
||||
|
||||
@@ -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
@@ -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
@@ -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)
|
||||
*/
|
||||
+1169
File diff suppressed because it is too large.
Load diff
@@ -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;
|
||||
}
|
||||
};
|
||||
@@ -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;
|
||||
@@ -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;
|
||||
@@ -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;
|
||||
@@ -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;
|
||||
@@ -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;
|
||||
@@ -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;
|
||||
@@ -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
@@ -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
@@ -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;
|
||||
}
|
||||
BIN
Binary file not shown.
-4
@@ -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
|
||||
+2241
-1113
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,37 @@
|
||||
// 引擎单文件打包(开发用):把 plugin/engine.js + potrace 打成 IIFE 全局 VZEngine,便于在
|
||||
// 浏览器里直接跑参数实验(tools/trace-cli.mjs 用它)。发布不走这里 —— 发布走根目录
|
||||
// scripts/build-plugin.mjs(esbuild → 单文件 IIFE 插件)。
|
||||
import path from 'node:path'
|
||||
import { fileURLToPath } from 'node:url'
|
||||
import { createRequire } from 'node:module'
|
||||
|
||||
const HERE = path.dirname(fileURLToPath(import.meta.url))
|
||||
const PLUGIN = path.resolve(HERE, '../plugin')
|
||||
const HOST_REPO = '/Users/qiqi/open/github/image-workbench-web'
|
||||
const REPO = path.resolve(HERE, '../..')
|
||||
|
||||
export function esbuildModule() {
|
||||
for (const base of [HOST_REPO, REPO, process.cwd()]) {
|
||||
try {
|
||||
return createRequire(path.join(base, 'package.json'))('esbuild')
|
||||
} catch {
|
||||
/* 试下一个 */
|
||||
}
|
||||
}
|
||||
throw new Error('找不到 esbuild(宿主仓 node_modules 里应该有)')
|
||||
}
|
||||
|
||||
export function bundleEngine(outfile = '/tmp/vz-engine.bundle.js') {
|
||||
const esbuild = esbuildModule()
|
||||
esbuild.buildSync({
|
||||
entryPoints: [path.join(PLUGIN, 'engine.js')],
|
||||
bundle: true,
|
||||
format: 'iife',
|
||||
globalName: 'VZEngine',
|
||||
platform: 'browser',
|
||||
target: ['chrome110'],
|
||||
outfile,
|
||||
logLevel: 'error',
|
||||
})
|
||||
return outfile
|
||||
}
|
||||
@@ -1,8 +1,9 @@
|
||||
// 真实站点端到端(开发用,不进 CI)。
|
||||
//
|
||||
// 与 harness 的分工:harness 用合成宿主,能验功能但不能验 CSP;这里走真站 ——
|
||||
// 真实的 `_headers`(含 'wasm-unsafe-eval')、真实 KV、浏览器 SRI 校验、真实画布桥。
|
||||
// 「wasm 能不能在宿主 CSP 下编译」只有这里能真验到。
|
||||
// 与 harness 的分工:harness 用合成宿主,能验功能但不能验真实 CSP/网络;这里走真站 ——
|
||||
// 真实的 `_headers`(**不含 wasm-unsafe-eval**)、真实 KV、浏览器 SRI 校验、真实画布桥。
|
||||
// v0.2 是纯 JS potrace,所以这里反而要断言「wasm 仍被 CSP 拦住」——防止有人为了别的功能
|
||||
// 悄悄把 'wasm-unsafe-eval' 加回去。
|
||||
//
|
||||
// 运行:
|
||||
// node image-vectorize/tools/e2e-site.mjs
|
||||
@@ -97,16 +98,15 @@ check('插件脚本用 SRI(sha256) 加载',
|
||||
scripts.some((s) => s.src.indexOf('/plugins/plugin-' + PLUGIN_ID + '.') === 0 && /^sha256-/.test(s.integrity)),
|
||||
JSON.stringify(scripts.map((s) => s.src)))
|
||||
|
||||
// ---------- 2) 宿主 CSP 放行 wasm(本插件存在的前提) ----------
|
||||
// ---------- 2) 宿主 CSP 不再放行 wasm(v0.2 纯 JS,不需要放宽) ----------
|
||||
const cspProbe = await page.evaluate(async () => {
|
||||
try {
|
||||
// (module) 最小 wasm,8 字节
|
||||
const b = Uint8Array.from(atob('AGFzbQEAAAA='), (c) => c.charCodeAt(0))
|
||||
await WebAssembly.instantiate(b)
|
||||
return 'ok'
|
||||
} catch (e) { return 'blocked: ' + e.message }
|
||||
})
|
||||
check('宿主 CSP 允许 wasm 编译(wasm-unsafe-eval)', cspProbe === 'ok', cspProbe.slice(0, 120))
|
||||
check('宿主 CSP 仍禁止 wasm 编译(本插件是纯 JS,不该再放宽)', cspProbe.indexOf('blocked') === 0, cspProbe.slice(0, 120))
|
||||
|
||||
// ---------- 3) 打开工作区 ----------
|
||||
await page.locator('.iwb-home-card:not(.iwb-home-new)').first().dblclick()
|
||||
@@ -137,18 +137,18 @@ const paths = await poll(async () => {
|
||||
const t = await page.locator('[data-stat="paths"]').textContent()
|
||||
return t && t !== '–' && Number(t) > 0 ? t : false
|
||||
}, 30000)
|
||||
check('真站描摹成功(wasm 编译 + 执行)', Boolean(paths), 'paths=' + paths)
|
||||
check('真站描摹成功(纯 JS 引擎,无 wasm)', Boolean(paths), 'paths=' + paths)
|
||||
check('预览为 blob: SVG', await page.evaluate(() => {
|
||||
const v = document.querySelector('[data-stage="vector"]')
|
||||
return Boolean(v && /^blob:/.test(v.src) && !v.hidden)
|
||||
}))
|
||||
|
||||
const stats = await page.evaluate(() => ({
|
||||
colors: Number(document.querySelector('[data-stat="colors"]').textContent),
|
||||
levels: Number(document.querySelector('[data-stat="levels"]').textContent),
|
||||
bytes: document.querySelector('[data-stat="bytes"]').textContent,
|
||||
ms: document.querySelector('[data-stat="ms"]').textContent,
|
||||
}))
|
||||
check('色层正常(≥3 色)', stats.colors >= 3, JSON.stringify(stats))
|
||||
check('灰度层数正常(3 层)', stats.levels >= 3, JSON.stringify(stats))
|
||||
|
||||
// ---------- 6) 保存为节点(真实画布桥) ----------
|
||||
await page.locator('[data-act="save"]').click()
|
||||
|
||||
+155
-103
@@ -1,11 +1,11 @@
|
||||
// 位图转矢量:本地端到端(开发用,不进 CI)。
|
||||
// 位图转矢量(potrace 单色/灰度):本地端到端(开发用,不进 CI)。
|
||||
//
|
||||
// 直接把构建产物注入合成宿主,在真实 Chromium 里验证:
|
||||
// 注册 / 模态 / wasm 引擎真跑出矢量 / 预设与参数联动 / 黑白模式禁用颜色项 /
|
||||
// 颜色精度区间保护 / 边缘净化 / SVG 下载 / 保存为 PNG 节点 / 空格对比 / Esc 关闭 / 参数记忆。
|
||||
// 注册 / 模态 / 单色描摹 / 灰度分层(层数联动)/ 参数联动 / 反相 / 去小点 / 颜色 /
|
||||
// 下载 SVG / 保存为 PNG 节点 / 空格对比 / Esc 关闭 / 参数记忆。
|
||||
//
|
||||
// 页面刻意带上宿主同款 CSP(script-src 无 unsafe-inline,但有 wasm-unsafe-eval),
|
||||
// 这样「wasm 能不能编译」这条约束是被真实测到的,而不是绕过去的。
|
||||
// 页面刻意带上**与线上同款的 CSP**(`script-src 'self'`,没有 wasm-unsafe-eval):
|
||||
// potrace 是纯 JS,这条断言顺带证明「本版不再需要放宽 CSP」。
|
||||
//
|
||||
// 运行:node image-vectorize/tools/harness.mjs
|
||||
// 依赖:playwright(本仓/宿主仓 node_modules 均可;或用 IWB_PLAYWRIGHT_ROOT 指定)
|
||||
@@ -35,17 +35,22 @@ const check = (name, ok, detail) => {
|
||||
console.log((ok ? '✓ ' : '✗ ') + name + (detail ? ' ' + detail : ''))
|
||||
}
|
||||
const sleep = (ms) => new Promise((r) => setTimeout(r, ms))
|
||||
// 描摹是异步的(wasm 一次几十毫秒 + 150ms 防抖),等统计数字出现即可
|
||||
const waitStats = async (page, timeout = 8000) => {
|
||||
const waitText = async (page, sel, timeout = 8000) => {
|
||||
const end = Date.now() + timeout
|
||||
for (;;) {
|
||||
const t = await page.locator('[data-stat="paths"]').textContent().catch(() => null)
|
||||
const t = await page.locator(sel).textContent().catch(() => null)
|
||||
if (t && t !== '–') return t
|
||||
if (Date.now() > end) return false
|
||||
await sleep(120)
|
||||
await sleep(100)
|
||||
}
|
||||
}
|
||||
const pathsNow = (page) => page.locator('[data-stat="paths"]').textContent()
|
||||
const levelsNow = (page) => page.locator('[data-stat="levels"]').textContent()
|
||||
const svgNow = (page) => page.evaluate(() => {
|
||||
const img = document.querySelector('[data-stage="vector"]')
|
||||
if (!img || !img.src) return ''
|
||||
return window.__lastSvg || ''
|
||||
})
|
||||
|
||||
const browser = await chromium.launch()
|
||||
const page = await browser.newPage({ viewport: { width: 1440, height: 1000 }, acceptDownloads: true })
|
||||
@@ -54,20 +59,23 @@ page.on('console', (m) => { if (m.type() === 'error') errors.push(m.text()) })
|
||||
page.on('pageerror', (e) => errors.push('pageerror: ' + e.message))
|
||||
page.on('dialog', (d) => { errors.push('unexpected dialog: ' + d.message()); d.dismiss().catch(() => {}) })
|
||||
|
||||
const CSP = "default-src 'self'; script-src 'self' 'wasm-unsafe-eval'; style-src 'unsafe-inline'; img-src data: blob:; connect-src https: http:"
|
||||
// 与线上 _headers 的 /* 组保持一致(**故意不带 wasm-unsafe-eval**)
|
||||
const CSP = "default-src 'self'; script-src 'self'; style-src 'unsafe-inline'; img-src data: blob:; connect-src https: http:"
|
||||
await page.setContent('<!doctype html><html><head><meta charset="utf-8"><meta http-equiv="Content-Security-Policy" content="' + CSP + '"><style>body{margin:0}</style></head><body><div id="host"></div></body></html>')
|
||||
|
||||
// 测试图:白底 + 红圆 + 蓝圆角矩形 + 黑色中文 + 绿色曲线(实心/圆角/文字/描边四类形态)
|
||||
// 测试图:白底 + 红圆 + 蓝圆角矩形 + 黑色中文 + 绿色曲线(实心/圆角/文字/描边四类形态),
|
||||
// 外加几个 1–2px 的孤立噪点(用来验证「去小点」真的吃掉它们)
|
||||
const PNG = await page.evaluate(() => {
|
||||
const c = document.createElement('canvas')
|
||||
c.width = 400; c.height = 400
|
||||
c.width = 480; c.height = 480
|
||||
const g = c.getContext('2d')
|
||||
g.fillStyle = '#ffffff'; g.fillRect(0, 0, 400, 400)
|
||||
g.fillStyle = '#e8422f'; g.beginPath(); g.arc(120, 120, 74, 0, Math.PI * 2); g.fill()
|
||||
g.fillStyle = '#1f5fa8'; g.beginPath(); g.roundRect(214, 164, 150, 104, 14); g.fill()
|
||||
g.fillStyle = '#111111'; g.font = 'bold 46px "PingFang SC", sans-serif'; g.fillText('菜单', 124, 310)
|
||||
g.strokeStyle = '#2e9e6b'; g.lineWidth = 4
|
||||
g.beginPath(); g.moveTo(60, 356); g.bezierCurveTo(150, 330, 260, 390, 350, 350); g.stroke()
|
||||
g.fillStyle = '#ffffff'; g.fillRect(0, 0, 480, 480)
|
||||
g.fillStyle = '#e8422f'; g.beginPath(); g.arc(140, 140, 88, 0, Math.PI * 2); g.fill()
|
||||
g.fillStyle = '#1f5fa8'; g.beginPath(); g.roundRect(252, 190, 176, 120, 16); g.fill()
|
||||
g.fillStyle = '#111111'; g.font = 'bold 54px "PingFang SC", sans-serif'; g.fillText('菜单', 146, 372)
|
||||
g.strokeStyle = '#2e9e6b'; g.lineWidth = 5
|
||||
g.beginPath(); g.moveTo(70, 428); g.bezierCurveTo(176, 396, 306, 468, 412, 420); g.stroke()
|
||||
for (const [x, y] of [[40, 40], [60, 44], [44, 62], [452, 60]]) g.fillRect(x, y, 2, 2)
|
||||
return c.toDataURL('image/png')
|
||||
})
|
||||
|
||||
@@ -77,10 +85,20 @@ await page.evaluate(() => {
|
||||
window.__commands = {}
|
||||
window.__settings = {}
|
||||
window.__writes = []
|
||||
// 抓每次产出的 SVG 原文:断言要能看内容(反相/颜色/层数),不能只数路径
|
||||
window.__svgSeq = 0
|
||||
window.__lastSvg = ''
|
||||
const origCreate = URL.createObjectURL.bind(URL)
|
||||
URL.createObjectURL = function (blob) {
|
||||
const url = origCreate(blob)
|
||||
if (blob && typeof blob.text === 'function' && String(blob.type || '').indexOf('image/svg') === 0) {
|
||||
blob.text().then((t) => { window.__lastSvg = t; window.__svgSeq++ })
|
||||
}
|
||||
return url
|
||||
}
|
||||
})
|
||||
|
||||
// 产物用 CDP 直接执行注入:本页带 CSP(script-src 无 unsafe-inline),addScriptTag 会被拦。
|
||||
// 这只影响「把代码装进页面」,插件运行时编译 wasm 仍受页面 CSP 约束 —— 那才是要测的点。
|
||||
await page.evaluate(readFileSync(PLUGIN_ENTRY, 'utf8'))
|
||||
|
||||
const boot = await page.evaluate((png) => {
|
||||
@@ -119,27 +137,30 @@ 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 声明了参数记忆项', ['preset', 'colorPrecision', 'denoise', 'outScale'].every((k) => boot.settings.includes(k)), boot.settings.length + ' 项')
|
||||
check('manifest 声明了参数记忆项', ['mode', 'levels', 'turdSize', 'alphaMax', 'invert', 'color', 'outScale'].every((k) => boot.settings.includes(k)), boot.settings.length + ' 项')
|
||||
check('capabilities 含 canvasWrite(要写回节点)', boot.capabilities.includes('canvasWrite'), boot.capabilities.join(','))
|
||||
|
||||
await page.evaluate(() => { window.__commands['vectorize-selected'].run().catch(() => {}) })
|
||||
// ---------- 打开模态 ----------
|
||||
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(() =>
|
||||
Boolean(document.querySelector('.vz-preview') && document.querySelector('.vz-panel') &&
|
||||
document.querySelector('[data-act="save"]') && document.querySelector('[data-act="svg"]') && document.querySelector('[data-act="cancel"]'))))
|
||||
|
||||
check('模态打开:预览区 + 参数面板 + 三个动作按钮齐全', await page.evaluate(() => {
|
||||
const q = (s) => Boolean(document.querySelector(s))
|
||||
return q('.vz-preview') && q('.vz-panel') && q('[data-act="cancel"]') && q('[data-act="svg"]') && q('[data-act="save"]')
|
||||
const p0 = await waitText(page, '[data-stat="paths"]')
|
||||
check('纯 JS 引擎在宿主 CSP 下跑通(无需 wasm-unsafe-eval)', Boolean(p0), 'paths=' + p0)
|
||||
check('默认预设「文字 / 线稿」= 单色', await page.evaluate(() => {
|
||||
const row = document.querySelector('[data-seg-group="mode"] button.active')
|
||||
return Boolean(row && row.dataset.value === 'mono')
|
||||
}))
|
||||
|
||||
const first = await waitStats(page)
|
||||
check('wasm 引擎首次描摹成功(CSP 下 wasm 可编译)', Boolean(first) && Number(first) > 0, 'paths=' + first)
|
||||
// ---------- 预览与棋盘 ----------
|
||||
check('预览是矢量(blob: SVG 且不是原图)', await page.evaluate(() => {
|
||||
const v = document.querySelector('[data-stage="vector"]')
|
||||
const o = document.querySelector('[data-stage="original"]')
|
||||
return Boolean(v && v.src.startsWith('blob:') && !v.hidden && o.hidden)
|
||||
return Boolean(v && /^blob:/.test(v.src) && !v.hidden)
|
||||
}))
|
||||
|
||||
// 透明区必须是中性灰棋盘:电商素材大量是黑字/深色 logo,深色棋盘会把内容直接吞掉,
|
||||
// 看起来像「描摹失败」(这个坑实测踩过一次)
|
||||
// 看起来像「描摹失败」(这个坑上一版实测踩过一次)
|
||||
check('预览透明底用浅色棋盘(深色内容不会被吞)', await page.evaluate(() => {
|
||||
const bg = getComputedStyle(document.querySelector('.vz-preview')).backgroundColor
|
||||
const m = /rgba?\((\d+),\s*(\d+),\s*(\d+)/.exec(bg)
|
||||
@@ -148,102 +169,133 @@ check('预览透明底用浅色棋盘(深色内容不会被吞)', await page
|
||||
return lum > 150
|
||||
}))
|
||||
|
||||
const stats = await page.evaluate(() => ({
|
||||
paths: Number(document.querySelector('[data-stat="paths"]').textContent),
|
||||
colors: Number(document.querySelector('[data-stat="colors"]').textContent),
|
||||
bytes: document.querySelector('[data-stat="bytes"]').textContent,
|
||||
ms: document.querySelector('[data-stat="ms"]').textContent,
|
||||
}))
|
||||
check('色层覆盖够用(红/蓝/黑/绿/白至少分 4 层)', stats.colors >= 4, JSON.stringify(stats))
|
||||
check('描摹耗时 < 3s(400×400 参考图)', Number(String(stats.ms).replace('ms', '')) < 3000, stats.ms)
|
||||
const monoPaths = Number(await pathsNow(page))
|
||||
const monoMs = Number((await page.locator('[data-stat="ms"]').textContent()).replace(/[^\d]/g, ''))
|
||||
check('单色描摹产出路径(文字图形都在)', monoPaths >= 1 && monoPaths <= 40, 'paths=' + monoPaths)
|
||||
check('描摹耗时 < 1.5s(480×480)', monoMs > 0 && monoMs < 1500, monoMs + 'ms')
|
||||
check('单色模式没有 fill-opacity(真单色,不是灰度伪装)', await page.evaluate(() => !/fill-opacity/.test(window.__lastSvg || '')), '')
|
||||
|
||||
check('默认预设为「标志 / 图标」且高亮', await page.evaluate(() => {
|
||||
const a = document.querySelector('.vz-preset.active')
|
||||
return Boolean(a && a.dataset.preset === 'logo')
|
||||
// ---------- 灰度分层 ----------
|
||||
await page.locator('[data-seg="mode"][data-value="gray"]').click()
|
||||
await sleep(400)
|
||||
const grayPaths = await waitText(page, '[data-stat="paths"]')
|
||||
const grayLevels = await levelsNow(page)
|
||||
check('切「灰度分层」:层数 = 3 且重新描摹', String(grayLevels) === '3' && Number(grayPaths) >= 3, 'paths=' + grayPaths + ' levels=' + grayLevels)
|
||||
check('灰度层数行可见、单色颜色项禁用', await page.evaluate(() => {
|
||||
const row = document.querySelector('[data-only="gray"]')
|
||||
const color = document.querySelector('[data-color="color"]')
|
||||
return Boolean(row && !row.hidden && color && color.disabled)
|
||||
}))
|
||||
|
||||
await page.locator('.vz-preset[data-preset="photo"]').click()
|
||||
await sleep(900)
|
||||
check('切「照片」预设:颜色精度→4 且重新描摹', await page.evaluate(() =>
|
||||
document.querySelector('[data-param="colorPrecision"]').value === '4' &&
|
||||
document.querySelector('.vz-preset[data-preset="photo"]').classList.contains('active')),
|
||||
'paths=' + await pathsNow(page))
|
||||
await page.locator('[data-seg="levels"][data-value="5"]').click()
|
||||
await sleep(500)
|
||||
check('层数切到 5:层数统计跟着变(自定义阈值数组生效)', String(await levelsNow(page)) === '5', 'levels=' + await levelsNow(page))
|
||||
await page.locator('[data-seg="levels"][data-value="3"]').click()
|
||||
await sleep(400)
|
||||
|
||||
// 手动拖滑杆即脱离预设(预设只是参数组合的快捷方式)
|
||||
// ---------- 去小点 ----------
|
||||
const beforeTurd = await pathsNow(page)
|
||||
await page.locator('[data-param="turdSize"]').fill('24')
|
||||
await sleep(450)
|
||||
const afterTurd = await waitText(page, '[data-stat="paths"]')
|
||||
check('去小点调大后重新描摹(噪点应被吃掉,路径不增)', Number(afterTurd) <= Number(beforeTurd), beforeTurd + ' → ' + afterTurd)
|
||||
await page.locator('[data-param="turdSize"]').fill('3')
|
||||
await sleep(400)
|
||||
|
||||
// ---------- 边缘(alphaMax) ----------
|
||||
const beforeTone = await page.evaluate(() => window.__svgSeq)
|
||||
await page.locator('[data-seg="alphaTone"][data-value="round"]').click()
|
||||
await sleep(450)
|
||||
check('边缘「圆润」触发重新描摹(换了一套几何)', (await page.evaluate(() => window.__svgSeq)) > beforeTone)
|
||||
await page.locator('[data-seg="alphaTone"][data-value="normal"]').click()
|
||||
await sleep(400)
|
||||
|
||||
// ---------- 反相 ----------
|
||||
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)
|
||||
await page.locator('[data-seg="invert"][data-value="0"]').click()
|
||||
await sleep(400)
|
||||
|
||||
// ---------- 阈值手动 ----------
|
||||
await page.locator('[data-seg="thrMode"][data-value="manual"]').click()
|
||||
await sleep(150)
|
||||
check('阈值切手动后滑杆出现', await page.evaluate(() => {
|
||||
const row = document.querySelector('[data-thr-row]')
|
||||
return Boolean(row && !row.hidden)
|
||||
}))
|
||||
await page.locator('[data-seg="thrMode"][data-value="auto"]').click()
|
||||
await sleep(300)
|
||||
|
||||
// ---------- 颜色(单色) ----------
|
||||
await page.locator('[data-seg="mode"][data-value="mono"]').click()
|
||||
await sleep(400)
|
||||
check('切回单色后颜色输入可用', await page.evaluate(() => {
|
||||
const c = document.querySelector('[data-color="color"]')
|
||||
return Boolean(c && !c.disabled)
|
||||
}))
|
||||
await page.evaluate(() => {
|
||||
const i = document.querySelector('[data-param="filterSpeckle"]')
|
||||
i.value = '20'
|
||||
i.dispatchEvent(new Event('input', { bubbles: true }))
|
||||
const c = document.querySelector('[data-color="color"]')
|
||||
c.value = '#c0392b'
|
||||
c.dispatchEvent(new Event('input', { bubbles: true }))
|
||||
})
|
||||
await sleep(700)
|
||||
check('手动改参数后脱离预设高亮', await page.evaluate(() => !document.querySelector('.vz-preset.active')))
|
||||
await sleep(400)
|
||||
check('改单色填充色写进 SVG', await page.evaluate(() => /#c0392b/i.test(window.__lastSvg || '')), '')
|
||||
|
||||
await page.locator('[data-seg-group="binary"] button[data-value="binary"]').click()
|
||||
await sleep(700)
|
||||
check('黑白模式禁用颜色精度/色层差异(不假装可调)', await page.evaluate(() =>
|
||||
document.querySelector('[data-param="colorPrecision"]').disabled &&
|
||||
document.querySelector('[data-param="layerDifference"]').disabled))
|
||||
check('黑白模式仍产出路径', await waitStats(page))
|
||||
|
||||
await page.locator('[data-seg-group="binary"] button[data-value="color"]').click()
|
||||
await sleep(700)
|
||||
check('切回彩色后颜色参数恢复可调', await page.evaluate(() => !document.querySelector('[data-param="colorPrecision"]').disabled))
|
||||
|
||||
// 实测:colorPrecision ≥6 会把整张图塌成一个色块,=8 直接 wasm abort,故滑杆必须夹在 1–5
|
||||
check('颜色精度被夹在 1–5(引擎安全区间)', await page.evaluate(() => {
|
||||
const i = document.querySelector('[data-param="colorPrecision"]')
|
||||
return i.min === '1' && i.max === '5'
|
||||
}))
|
||||
|
||||
await page.locator('[data-seg-group="denoise"] button[data-value="3"]').click()
|
||||
await sleep(1100)
|
||||
check('边缘净化 1/3:重新描摹并保持可用', Boolean(await waitStats(page)) &&
|
||||
await page.evaluate(() => document.querySelector('[data-seg-group="denoise"] button.active')?.dataset.value === '3'),
|
||||
'paths=' + await pathsNow(page))
|
||||
|
||||
const dlPromise = page.waitForEvent('download', { timeout: 12000 }).catch(() => null)
|
||||
// ---------- 输出 ----------
|
||||
const dl = page.waitForEvent('download', { timeout: 8000 })
|
||||
await page.locator('[data-act="svg"]').click()
|
||||
const download = await dlPromise
|
||||
check('「下载 SVG」触发文件下载', Boolean(download) && /\.svg$/.test(download.suggestedFilename() || ''), download ? download.suggestedFilename() : 'no download')
|
||||
const download = await dl
|
||||
check('「下载 SVG」触发文件下载', /\.svg$/.test(download.suggestedFilename()), download.suggestedFilename())
|
||||
|
||||
await page.locator('[data-act="save"]').click()
|
||||
await sleep(1400)
|
||||
const wrote = await page.evaluate(() => window.__writes[0])
|
||||
check('「保存为节点」写出 PNG 图片节点', Boolean(wrote) && wrote.kind === 'newNode' && wrote.head.startsWith('data:image/png'),
|
||||
wrote ? JSON.stringify({ kind: wrote.kind, head: wrote.head, kb: Math.round(wrote.len / 1024) + 'KB' }) : 'no write')
|
||||
await sleep(900)
|
||||
check('「保存为节点」写出 PNG 图片节点', await page.evaluate(() =>
|
||||
window.__writes.some((w) => w.kind === 'newNode' && /^data:image\/png;base64,/.test(w.head))),
|
||||
JSON.stringify(await page.evaluate(() => window.__writes.slice(-1))))
|
||||
check('保存后模态自动关闭', (await page.locator('.vz-root').count()) === 0)
|
||||
|
||||
check('参数记忆写回宿主 settings', await page.evaluate(() => {
|
||||
const s = window.__settings
|
||||
return Number(s.outScale) === 2 && Number(s.denoise) === 3 && s.binary === false && Number(s.filterSpeckle) === 20
|
||||
}), await page.evaluate(() => JSON.stringify(window.__settings)))
|
||||
|
||||
// 重新打开应沿用上次参数
|
||||
await page.evaluate(() => { window.__commands['vectorize-selected'].run().catch(() => {}) })
|
||||
// ---------- 参数记忆 ----------
|
||||
const mem = await page.evaluate(() => window.__settings)
|
||||
check('参数记忆写回宿主 settings', mem && mem.mode === 'mono' && Number(mem.turdSize) === 3 && String(mem.color).toLowerCase() === '#c0392b', JSON.stringify(mem))
|
||||
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 })
|
||||
await waitStats(page)
|
||||
check('重新打开沿用上次参数(filterSpeckle=20、denoise=1/3)', await page.evaluate(() =>
|
||||
document.querySelector('[data-param="filterSpeckle"]').value === '20' &&
|
||||
document.querySelector('[data-seg-group="denoise"] button.active')?.dataset.value === '3'))
|
||||
check('重新打开沿用上次参数(mode=mono、颜色 #c0392b)', await page.evaluate(() => {
|
||||
const active = document.querySelector('[data-seg-group="mode"] button.active')
|
||||
const color = document.querySelector('[data-color="color"]')
|
||||
return Boolean(active && active.dataset.value === 'mono' && color && color.value.toLowerCase() === '#c0392b')
|
||||
}))
|
||||
|
||||
// 空格对比原图
|
||||
// ---------- 空格对比 / Esc ----------
|
||||
await page.evaluate(() => document.body.focus())
|
||||
await page.keyboard.down('Space')
|
||||
await sleep(220)
|
||||
const spaceOn = await page.evaluate(() => !document.querySelector('[data-stage="original"]').hidden && document.querySelector('[data-badge]').textContent === '原图')
|
||||
await sleep(150)
|
||||
check('按住空格对比原图', await page.evaluate(() => {
|
||||
const o = document.querySelector('[data-stage="original"]')
|
||||
return Boolean(o && !o.hidden)
|
||||
}))
|
||||
await page.keyboard.up('Space')
|
||||
await sleep(220)
|
||||
const spaceOff = await page.evaluate(() => document.querySelector('[data-stage="original"]').hidden)
|
||||
check('按住空格对比原图、松开回到矢量', spaceOn && spaceOff)
|
||||
await sleep(120)
|
||||
check('松开空格回到矢量', await page.evaluate(() => {
|
||||
const o = document.querySelector('[data-stage="original"]')
|
||||
const v = document.querySelector('[data-stage="vector"]')
|
||||
return Boolean(o && o.hidden && v && !v.hidden)
|
||||
}))
|
||||
|
||||
await page.keyboard.press('Escape')
|
||||
await sleep(400)
|
||||
await sleep(200)
|
||||
check('Esc 关闭模态', (await page.locator('.vz-root').count()) === 0)
|
||||
|
||||
const fatal = errors.filter((e) => /Content Security Policy|Refused to|WebAssembly|is not defined|TypeError/i.test(e))
|
||||
check('无 CSP / 运行时错误', fatal.length === 0, fatal.slice(0, 2).join(' | '))
|
||||
if (errors.length) {
|
||||
console.log('')
|
||||
console.log('页面错误:')
|
||||
for (const e of errors.slice(0, 6)) console.log(' ' + e)
|
||||
console.log('控制台错误(' + errors.length + ' 条,前 5 条):')
|
||||
for (const e of errors.slice(0, 5)) console.log(' ' + String(e).slice(0, 180))
|
||||
}
|
||||
|
||||
console.log('')
|
||||
console.log(failed ? '✗ 失败 ' + failed + ' 项' : '✓ 全部通过')
|
||||
await browser.close()
|
||||
|
||||
@@ -0,0 +1,134 @@
|
||||
// 单色/灰度描摹 CLI(开发用,不进 CI):把真实素材丢进去,直接看参数效果。
|
||||
//
|
||||
// node image-vectorize/tools/trace-cli.mjs <图片> [--mode mono|gray] [--levels 3]
|
||||
// [--turd 3] [--alpha 1] [--invert] [--color #1a1a1a] [--threshold -1] [--out 目录]
|
||||
//
|
||||
// 产物:<out>/<name>-<mode><levels>.svg + 一张对比图 <out>/<name>-cmp.png(原图 / 结果 / 局部放大)。
|
||||
// 为什么走浏览器:PNG/JPEG 解码和 ImageData 语义都与线上一致,Node 里没有等价的零依赖解码器。
|
||||
import { createRequire } from 'node:module'
|
||||
import fs from 'node:fs'
|
||||
import path from 'node:path'
|
||||
import { fileURLToPath } from 'node:url'
|
||||
import { bundleEngine } from './bundle-engine.mjs'
|
||||
|
||||
const HERE = path.dirname(fileURLToPath(import.meta.url))
|
||||
const REPO = path.resolve(HERE, '../..')
|
||||
const HOST_REPO = '/Users/qiqi/open/github/image-workbench-web'
|
||||
|
||||
let chromium = null
|
||||
for (const base of [HOST_REPO, REPO, process.cwd()]) {
|
||||
try {
|
||||
chromium = createRequire(path.join(base, 'package.json'))('playwright').chromium
|
||||
break
|
||||
} catch {
|
||||
/* 试下一个 */
|
||||
}
|
||||
}
|
||||
if (!chromium) {
|
||||
console.error('✗ 找不到 playwright')
|
||||
process.exit(2)
|
||||
}
|
||||
|
||||
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' }
|
||||
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 === '--invert') opt.invert = true
|
||||
else if (a === '--color') opt.color = argv[++i]
|
||||
else if (a === '--threshold') opt.threshold = Number(argv[++i])
|
||||
else if (a === '--out') opt.out = argv[++i]
|
||||
else if (a.startsWith('--')) throw new Error('未知参数 ' + a)
|
||||
else files.push(a)
|
||||
}
|
||||
if (!files.length) {
|
||||
console.error('用法:node image-vectorize/tools/trace-cli.mjs <图片...> [--mode mono|gray] [--levels 3] ...')
|
||||
process.exit(2)
|
||||
}
|
||||
fs.mkdirSync(opt.out, { recursive: true })
|
||||
|
||||
const bundle = bundleEngine()
|
||||
const bundleCode = fs.readFileSync(bundle, 'utf8')
|
||||
const browser = await chromium.launch()
|
||||
const page = await browser.newPage()
|
||||
await page.setContent('<canvas id="c"></canvas>')
|
||||
await page.addScriptTag({ content: bundleCode })
|
||||
|
||||
const params = {
|
||||
mode: opt.mode,
|
||||
levels: opt.levels,
|
||||
turdSize: opt.turd,
|
||||
alphaMax: opt.alpha,
|
||||
invert: opt.invert,
|
||||
color: opt.color,
|
||||
threshold: opt.threshold,
|
||||
outScale: 1,
|
||||
}
|
||||
|
||||
for (const file of files) {
|
||||
const b64 = fs.readFileSync(file).toString('base64')
|
||||
const mime = /\.jpe?g$/i.test(file) ? 'image/jpeg' : 'image/png'
|
||||
const res = await page.evaluate(
|
||||
async ({ dataUrl, params }) => {
|
||||
const img = new Image()
|
||||
img.src = dataUrl
|
||||
await img.decode()
|
||||
const c = document.createElement('canvas')
|
||||
c.width = img.naturalWidth
|
||||
c.height = img.naturalHeight
|
||||
const g = c.getContext('2d', { willReadFrequently: true })
|
||||
g.drawImage(img, 0, 0)
|
||||
const imageData = g.getImageData(0, 0, c.width, c.height)
|
||||
const out = window.VZEngine.traceImageData(imageData, params)
|
||||
return { svg: out.svg, ms: out.ms, paths: out.paths, levels: out.levels, w: c.width, h: c.height }
|
||||
},
|
||||
{ dataUrl: `data:${mime};base64,${b64}`, params }
|
||||
)
|
||||
const base = path.basename(file).replace(/\.[^.]+$/, '')
|
||||
const tag = opt.mode === 'mono' ? 'mono' : 'gray' + res.levels
|
||||
const svgPath = path.join(opt.out, `${base}-${tag}.svg`)
|
||||
fs.writeFileSync(svgPath, res.svg)
|
||||
console.log(
|
||||
`${base} ${tag.padEnd(6)} ${String(res.paths).padStart(3)} paths ${String(res.ms).padStart(4)}ms ` +
|
||||
`${(res.svg.length / 1024).toFixed(0)}KB ${res.w}×${res.h} → ${svgPath}`
|
||||
)
|
||||
|
||||
// 对比图:原图 | 描摹结果
|
||||
const cmp = await page.evaluate(
|
||||
async ({ orig, svg, w, h }) => {
|
||||
const load = (src) => new Promise((res, rej) => { const i = new Image(); i.onload = () => res(i); i.onerror = rej; i.src = src })
|
||||
const a = await load(orig)
|
||||
const b = await load('data:image/svg+xml;base64,' + btoa(unescape(encodeURIComponent(svg))))
|
||||
const cw = 520
|
||||
const ch = Math.round((h / w) * cw)
|
||||
const cv = document.createElement('canvas')
|
||||
cv.width = cw * 2 + 16
|
||||
cv.height = ch + 24
|
||||
const g = cv.getContext('2d')
|
||||
g.fillStyle = '#fff'
|
||||
g.fillRect(0, 0, cv.width, cv.height)
|
||||
g.drawImage(a, 0, 20, cw, ch)
|
||||
g.drawImage(b, cw + 16, 20, cw, ch)
|
||||
g.fillStyle = '#333'
|
||||
g.font = '12px system-ui'
|
||||
g.fillText('原图', 4, 14)
|
||||
g.fillText('描摹结果', cw + 20, 14)
|
||||
return cv.toDataURL('image/png')
|
||||
},
|
||||
{
|
||||
orig: `data:${mime};base64,${b64}`,
|
||||
svg: res.svg.replace(/fill-opacity="0"/g, 'fill-opacity="0.001"'),
|
||||
w: res.w,
|
||||
h: res.h,
|
||||
}
|
||||
)
|
||||
const cmpPath = path.join(opt.out, `${base}-cmp.png`)
|
||||
fs.writeFileSync(cmpPath, Buffer.from(cmp.split(',')[1], 'base64'))
|
||||
console.log(' 对比图 → ' + cmpPath)
|
||||
}
|
||||
|
||||
await browser.close()
|
||||
Reference in new issue
Block a user