Compare commits

...
Author SHA1 Message Date
qiqi 6e1685998f fix(image-annotate): v1.8.2 选择框控制点尺寸固定为屏幕像素
现象:选中图形时,控制点巨大(约 100px 的发光方块),大小随图片尺寸变化、与缩放无关。

根因:控制点、旋转手柄、虚线间距、命中半径全部写成 5.5 / S.zoom。
但 S.zoom 是「相对 fitW 的倍数」,不是「图片像素→屏幕像素」的比例。叠加 overlay
画布按 viewScale 拉伸后,真实屏幕尺寸 = 11 * fitW / imgW —— 只跟图片尺寸走:
小图被适应窗口放大 5~10 倍时膨胀到 100px,大图缩到 4px 看不见。
zoomStep 的 anchor 换算是另一个语义(相对 fitW 单位),保持 / S.zoom 不动。

顺带发现第二个问题:overlay 画布的像素缓冲等于图片尺寸,小图放大后 UI 叠层糊成光斑。

修法:
- 新增 plugin/editor/scale.js(零依赖叶子模块)
  viewScale() = fitW*zoom/imgW;overlayScale() = clamp(fitW/imgW, 1, 4);
  resetOverlayTransform(cx) = 恢复「图片坐标 + pad + 倍率」
- 7 个文件共 30 余处 UI 常量改为 X / viewScale();去掉 Math.max(X/zoom, N)
  的托底(N 是图片单位,放大时会变成巨大命中区,导致误触)
- overlay / selection / cursor 三张画布按 overlayScale 建缓冲,绘制坐标仍是图片单位,
  所以全部绘制代码无需改动;四处置空函数(crop/selection/tools/index)改用设备像素
  clearRect + resetOverlayTransform 恢复

必须做成叶子模块:viewport 与 crop/objects/layers 存在循环 import,把换算放在循环里
esbuild 打成 IIFE 后另一侧拿到 undefined —— 实测 clearOverlay 报
"resetOverlayTransform is not defined",编辑器直接打不开(已踩过)。

实测(Playwright 按屏幕分辨率重采样后量像素包围盒):
  96x64    控制点 7~8px   旧实现 101.5px   overlay 288x256 -> 1152x1024
  800x600  控制点 8~9px   旧实现 12.2px
  2400x1800 控制点 9~10px 旧实现 4.1px
纯白内区比视觉尺寸小 1.5px(描边压边),视觉上稳定 11px。

验证:harness 140 项全通(新增 1 项控制点尺寸断言)、validate 9/9。
2026-11-08 17:49:16 +08:00
qiqi fccb9ae69e fix(image-annotate): v1.8.1 修复 SRI 加载失败(发布改内容寻址文件名)
线上报「脚本完整性校验失败(integrity 不符或加载失败)」,插件不可用。

根因不在插件代码,在发布通道:scripts/plugins-publish.sh 用固定名
plugin-image-annotate.js,而清单 integrity 随内容每次变化。客户端只要留着
旧字节(浏览器磁盘/内存缓存、中间代理),新 integrity 就对不上,SRI 判失败。
no-cache + ETag 只是「可缓存但须回源校验」,管不住已到手的旧副本。
实测服务器端三处一致(清单 integrity = 线上字节 = 本地字节,355289 B),
证明问题完全在客户端拿到的那份。

修法(宿主仓同步改 scripts/plugins-publish.sh):文件名改为内容寻址
plugin-<id>.<sha256前12位>.js,与 plugins-publish.mjs 的 storedNameOf 对齐。
内容变 ⇒ 名变 ⇒ 新版本必然是新 URL,SRI 必中;同时命中 Functions 的
IMMUTABLE_JS_RE,拿到 public, max-age=31536000, immutable。

插件本体与 1.8.0 逐字相同,产物仅 manifest 版本号不同。
验证:harness 139 项全通、validate 9/9、产物 355289 B。
2026-11-08 17:13:06 +08:00
qiqi 3819048e54 feat(image-annotate): v1.8.0 快速效果加参数(马赛克块大小 / 柔化半径 / 其余强度)
v1.4 的六个效果都是一键定死强度:马赛克在 800px 图上固定 13px 块挡不住手机号,
柔化固定 1.6px 小图上几乎看不出。现在每个效果都带参数,点完还能继续拖。

参数模型:
- 百分比类(反白/灰度/增强/高对比):强度 0~100%,走 invert()/grayscale() 原生比例,
  其余按 k 插值(高对比 = grayscale(k) contrast(1+1.4k))
- 物理量类:柔化半径 0~16px、马赛克块大小 2~96px,默认值按短边缩放

关键设计:效果不能叠加在自己的结果上。
点效果时把目标层像素备份进 S.fx.source,拖滑杆一律「先还原 source 再按新参数渲染」。
否则「马赛克 12 → 48 → 12」会做三次重采样,块越来越碎且不可逆。

交互约定:
- 一次效果 = 一条撤销(点效果时快照,拖滑杆不再拍)
- 同效果再点 = 回默认值,不再糊一层
- 切到别的层滑杆置灰(源属于旧层),切回自动恢复
- 当前生效效果描橙边;拖滑杆不重建图层面板(否则每帧 innerHTML 会闪)

顺带修了两处既有缺陷:
- .iwb-editor-fx-target 标签从来没被更新过,一直显示「原图」——现在跟随目标层
- 柔化默认过弱(1.6px / 800px 图)——系数改 400、下限 1.2

验证:harness 139 项全通(新增 6 项,含「12→48→12 像素指纹一致」的叠加检测)、
validate 9/9、产物 341608 B。
2026-11-08 17:06:56 +08:00
qiqi eb90939f11 test(image-annotate): 真站 e2e 的 SRI 断言不再写死内容寻址文件名
断言原本要求 src 必须是 plugin-image-annotate.<hash12>.js,但带主干守卫的
合规发布通道 scripts/plugins-publish.sh 产出的是固定名 plugin-image-annotate.js
(走 no-cache + ETag),于是发布成功后这条断言必红、其余 26 项全绿。

SRI 的实质要求是「带 integrity 且有值」,与命名策略无关,改为两种命名都接受。
1.7.0 实测:test 站 27 项全通。
2026-11-08 16:54:50 +08:00
19 changed files with 1048 additions and 203 deletions

No files matched your search

+82
View File
@@ -234,6 +234,88 @@ P 下双击 = 结束当前路径(`commitPenPath`),不再进节点编辑。
- 文字 / 形状 / 钢笔会被直接栅格化进结果层(PS 合并矢量层也是这个结果)。
- 结果层落回「原最低参与层」的位置,`assignLayerZ` 重新连续编号,不产生重复 z。
## v1.8.2:选择框控制点尺寸固定为屏幕像素
选中图形 / 文字 / 位图时,控制点、旋转手柄、虚线间距、命中半径原本一律写成
`5.5 / S.zoom`。但 `S.zoom` 是「**相对 fitW 的倍数**」,不是「图片像素 → 屏幕像素」的比例。
叠上 overlay 画布按 viewScale 拉伸后,控制点的真实屏幕尺寸变成 `11 × fitW / imgW`:
**只跟图片尺寸走,和缩放完全无关**。小图被「适应窗口」放大 5~10 倍时,控制点会膨胀成
100px 的发光团(截图里那种),大图则缩成看不见的点。
修法:新增 `plugin/editor/scale.js`(零依赖叶子模块)
| 导出 | 含义 |
| --- | --- |
| `viewScale()` | `fitW × zoom / imgW` —— 1 个图片像素 = 多少屏幕 CSS 像素 |
| `overlayScale()` | `clamp(fitW / imgW, 1, 4)` —— overlay 画布的像素倍率 |
| `resetOverlayTransform(cx)` | 清屏后把 ctx 恢复成「图片坐标 + pad + 倍率」 |
- 所有「屏幕上恒定」的量改成 `X / viewScale()`:控制点 11px、虚线 1.5px、命中半径 11~16px
- 原先 `Math.max(X / zoom, N)` 的托底值 `N` 是**图片单位**,放大时会变成巨大的命中区(误触),一并去掉
- `viewScale()` 必须来自叶子模块:viewport 与 crop / objects / layers 互相 import,
把换算放在循环里,esbuild 打成 IIFE 后另一侧会拿到 undefined(实测报
`resetOverlayTransform is not defined`,编辑器直接打不开)
顺带修第二个问题:overlay 画布的像素缓冲原本等于图片尺寸,小图放大后控制点糊成一片光斑。
现在按 `overlayScale()` 建缓冲(96×64 → 1152×1024),绘制坐标仍是图片单位
(transform 里已含倍率),所以全部绘制代码不用改。上限 4 是为内存,缓冲面积按平方增长。
**实测**(Playwright 按屏幕分辨率重采样后量像素):96×64 / 800×600 / 2400×1800 三张图,
控制点屏幕尺寸 7~10px(视觉 11px —— 纯白内区比外框小 1.5px 描边):
旧实现分别是 **101.5 / 12.2 / 4.1px**。harness 新增 1 项断言守住这条。
## v1.8.1:修复 SRI 加载失败(发布通道改内容寻址)
v1.8.0 上线后线上报「脚本完整性校验失败(integrity 不符或加载失败)」,插件直接不可用。
原因不在插件代码,在发布通道:`scripts/plugins-publish.sh` 用的是**固定文件名**
`plugin-image-annotate.js`,而清单里的 `integrity` 随内容每次变化。
客户端只要还留着旧字节(浏览器磁盘/内存缓存、中间代理),新 integrity 就对不上 ⇒ SRI 判失败。
`no-cache + ETag` 的语义只是「可缓存但须回源校验」,管不住已经骗到手的旧副本。
修法:文件名改为内容寻址 `plugin-image-annotate.<sha256前12位>.js`,与 `plugins-publish.mjs`
的 `storedNameOf` 对齐。内容变 ⇒ 文件名变 ⇒ 新版本必然是新 URL,SRI 必中;
同时命中 Functions 的 `IMMUTABLE_JS_RE`,拿到 `public, max-age=31536000, immutable`,
355KB 的产物不必每次 304 回源协商。
插件本体代码与 v1.8.0 逐字相同,`src/index.js` 只有 manifest 里的版本号不同。
## v1.8:快速效果可调参数
v1.4 的六个效果都是一键定死强度:「马赛克」在 800px 图上固定 13px 块,挡不住手机号;
「柔化」固定 1.6px,小图上几乎看不出模糊。现在每个效果都带参数,点完还能继续调。
| 效果 | 参数 | 范围 | 默认 |
| --- | --- | --- | --- |
| 反白 | 强度 | 0–100% | 100% |
| 灰度 | 强度 | 0–100% | 100% |
| 增强 | 强度 | 0–100% | 100% |
| 高对比 | 强度 | 0–100% | 100% |
| 柔化 | 半径 | 0–16 px | 短边/400,钳在 1.2–8 |
| 马赛克 | 块大小 | 2–96 px | 短边/60,最小 6 |
强度 0 等于不处理。百分比类走 `invert()` / `grayscale()` 的原生比例,其余按强度插值
(如高对比:`grayscale(k) contrast(1 + 1.4k)`)。
### 关键:不能在自己的结果上叠加
点效果时把目标层像素备份进 `S.fx.source`,之后拖滑杆一律「先还原 source,再按新参数渲染」。
否则「马赛克 12 → 48 → 12」会做三次重采样,块越来越碎且不可逆。
回归用整层像素指纹断言:`12px → 48px → 12px` 的最终结果必须与首次 12px 逐字节一致。
### 交互约定
| 约定 | 原因 |
| --- | --- |
| 一次效果 = 一条撤销 | 点效果时拍快照,拖滑杆不再拍(连续拖 3 次,历史 0 新增) |
| 同效果再点 = 回默认值 | 不是再糊一层;`toast` 会说明重置成了多少 |
| 切到别的层滑杆置灰 | 源属于旧层,写进新层就是错的;切回原层自动恢复可用 |
| 当前效果按钮描橙边 | 拖动时要能看出在调哪个效果 |
| 拖滑杆不重建图层面板 | 否则拖动中每帧 `innerHTML` 会闪;缩略图与状态栏在松手(`change`)时统一刷新 |
`S.fx` 在 `resetState()` 与 `releaseEditorMemory()` 里都要清 —— 又一张全幅位图的引用。
## v1.7:图层面板补齐(缩略图 / 改名 / 不透明度)
发布后通读全仓(10 个模块 9368 行)发现的缺口,按「改完就能天天用到」的顺序处理。
+1 -1
View File
@@ -1,7 +1,7 @@
{
"name": "@iwb-plugin/image-annotate",
"private": true,
"version": "1.7.0",
"version": "1.8.2",
"description": "IWB 插件:图片标注 / 修图(编辑器移植自 iwb-plaus 扩展,纯 Canvas 2D)",
"ibwPlugin": {
"id": "image-annotate",
+46
View File
@@ -1757,6 +1757,13 @@
.iwb-editor-fx-btn:hover { background: #313244; border-color: #45475a; }
.iwb-editor-fx-btn:active { transform: scale(0.96); }
.iwb-editor-fx-btn:focus-visible { outline: 2px solid #89b4fa; outline-offset: 1px; }
/* v1.8:当前生效的效果。必须与 hover 一眼区分 —— 拖动强度滑杆时要能看出在调哪个效果 */
.iwb-editor-fx-btn.is-active {
background: #2c2735; border-color: #e8a735; color: #f3dcb0;
}
.iwb-editor-fx-btn.is-active .iwb-editor-fx-ico {
box-shadow: inset 0 0 0 1px rgba(232, 167, 53, 0.75);
}
.iwb-editor-fx-ico {
width: 22px; height: 22px; border-radius: 5px; display: block;
background-color: #d9d9e3;
@@ -1780,6 +1787,45 @@
margin: 0; font-size: 10px; line-height: 1.55; color: #6c7086;
}
/* v1.8:效果参数滑杆。范围与单位随效果切换(马赛克=块大小 px、柔化=半径 px、其余=强度 %)。
未点效果 / 目标层被切走时加 .iwb-editor-fx-adj-off 整条置灰。 */
.iwb-editor-fx-adj {
display: flex; flex-direction: column; gap: 4px;
padding: 6px 8px 5px; border-radius: 7px;
background: #1e1e2c; border: 1px solid #2f2f42;
transition: opacity 0.12s ease;
}
.iwb-editor-fx-adj-head {
display: flex; align-items: center; justify-content: space-between; gap: 6px;
}
.iwb-editor-fx-adj-name {
font-size: 10.5px; font-weight: 500; color: #b9c0d8;
overflow: hidden; text-overflow: ellipsis; white-space: nowrap;
}
.iwb-editor-fx-adj-val {
font-size: 10.5px; color: #e8a735; font-variant-numeric: tabular-nums; flex: 0 0 auto;
}
.iwb-editor-fx-adj-off { opacity: 0.5; }
.iwb-editor-fx-range {
-webkit-appearance: none; appearance: none;
width: 100%; height: 14px; margin: 0; background: transparent; cursor: pointer;
}
.iwb-editor-fx-range::-webkit-slider-runnable-track { height: 4px; border-radius: 2px; background: #313244; }
.iwb-editor-fx-range::-webkit-slider-thumb {
-webkit-appearance: none; appearance: none;
width: 12px; height: 12px; margin-top: -4px; border-radius: 50%;
background: #e8a735; border: 1px solid #1e1e2c;
box-shadow: 0 1px 2px rgba(0, 0, 0, 0.45);
}
.iwb-editor-fx-range::-moz-range-track { height: 4px; border-radius: 2px; background: #313244; }
.iwb-editor-fx-range::-moz-range-thumb {
width: 12px; height: 12px; border-radius: 50%; background: #e8a735; border: 1px solid #1e1e2c;
}
.iwb-editor-fx-range:disabled { cursor: default; }
.iwb-editor-fx-range:disabled::-webkit-slider-thumb { background: #585b70; }
.iwb-editor-fx-range:disabled::-moz-range-thumb { background: #585b70; }
.iwb-editor-fx-range:focus-visible { outline: 2px solid #89b4fa; outline-offset: 2px; }
/* ================================================================
v1.6:图层面板多选(⌘/Ctrl 点击)+ 合并按钮
多选用青色侧条与单选(橙色 #e8a735)区分:一个图层可以「被选中但不在合并集合里」,
+13 -11
View File
@@ -7,6 +7,7 @@
import { S, runtime } from './state.js'
import { resizeWorkspace } from './viewport.js'
import { resetOverlayTransform, viewScale } from './scale.js'
import { disposeSelection } from './selection.js'
import { saveSnapshot } from './history.js'
import { toast } from './commands.js'
@@ -82,12 +83,13 @@ import { toast } from './commands.js'
export function clearOverlay() {
const ctx = S.overlayCtx
const pad = S.overlayPad || 0
ctx.save()
ctx.setTransform(1, 0, 0, 1, 0, 0)
ctx.clearRect(0, 0, S.imgW + pad * 2, S.imgH + pad * 2)
ctx.restore()
ctx.setTransform(1, 0, 0, 1, pad, pad)
if (!ctx) return
// 缓冲已按 overlayScale 放大,必须按设备像素整幅清,再恢复图片坐标基准
ctx.save()
ctx.setTransform(1, 0, 0, 1, 0, 0)
ctx.clearRect(0, 0, ctx.canvas.width, ctx.canvas.height)
ctx.restore()
resetOverlayTransform(ctx)
}
export function drawCropPreview(x1, y1, x2, y2) {
@@ -112,8 +114,8 @@ import { toast } from './commands.js'
ctx.restore()
ctx.save()
ctx.strokeStyle = '#4488ff'
ctx.lineWidth = 2 / S.zoom
ctx.setLineDash([8 / S.zoom, 4 / S.zoom])
ctx.lineWidth = 2 / viewScale()
ctx.setLineDash([8 / viewScale(), 4 / viewScale()])
ctx.strokeRect(rx, ry, rw, rh)
ctx.restore()
if (S.cropRect && !S.cropHandle) drawCropHandles(rx, ry, rw, rh)
@@ -131,11 +133,11 @@ import { toast } from './commands.js'
function drawCropHandles(rx, ry, rw, rh) {
const ctx = S.overlayCtx
const pts = cropHandlePoints(rx, ry, rw, rh)
const hs = 4 / S.zoom
const hs = 4 / viewScale()
ctx.save()
ctx.fillStyle = '#ffffff'
ctx.strokeStyle = '#4488ff'
ctx.lineWidth = 1.5 / S.zoom
ctx.lineWidth = 1.5 / viewScale()
for (const name in pts) {
ctx.beginPath()
ctx.rect(pts[name][0] - hs, pts[name][1] - hs, hs * 2, hs * 2)
@@ -153,7 +155,7 @@ import { toast } from './commands.js'
export function hitCropHandle(pos) {
if (!S.cropRect) return null
const pts = cropHandlePoints(S.cropRect.x, S.cropRect.y, S.cropRect.w, S.cropRect.h)
const R = 12 / S.zoom
const R = 12 / viewScale()
let best = null, bestDist = 1e9
for (const name in pts) {
const dx = pos.x - pts[name][0], dy = pos.y - pts[name][1]
+9 -1
View File
@@ -194,7 +194,15 @@ import { bindEvents } from './events.js'
<span class="iwb-editor-fx-ico ico-mosaic"></span><span>马赛克</span>
</button>
</div>
<p class="iwb-editor-fx-tip">作用于当前层 · Ctrl+Z 可撤销</p>
<!-- v1.8:效果参数。点效果后启用,范围/单位随效果切换(马赛克=块大小,柔化=半径,其余=强度) -->
<div class="iwb-editor-fx-adj iwb-editor-fx-adj-off">
<div class="iwb-editor-fx-adj-head">
<span class="iwb-editor-fx-adj-name">强度</span>
<span class="iwb-editor-fx-adj-val">—</span>
</div>
<input type="range" class="iwb-editor-fx-range" min="0" max="100" step="1" value="0" disabled aria-label="效果强度">
</div>
<p class="iwb-editor-fx-tip">先点效果,再拖强度微调 · Ctrl+Z 撤销</p>
</section>
<div class="iwb-editor-zoom">
+192 -25
View File
@@ -1,4 +1,4 @@
/* effects.js - 侧栏「快速效果」(v1.4)
/* effects.js - 侧栏「快速效果」(v1.4,v1.8 加可调参数)
*
* 作用对象只有一个:当前位图图层(侧栏标题后面实时显示层名)。
* 全部走 canvas 2D 的 ctx.filter / 缩放重采样,不引入依赖、不动矢量层、
@@ -7,38 +7,82 @@
* 撤销:应用前 saveSnapshot()。base 与画笔层走像素快照(putImageData),
* 天然可回退;导入图片层走 image/sourceCanvas 重绘,原地改像素会被下一次
* 重绘冲掉,所以先按 PS「栅格化」的做法落一个普通位图副本(原层隐藏)。
*
* v1.8 可调参数的关键设计:**效果不能叠加在自身结果上**。
* 点效果时把目标层当时的像素备份进 S.fx.source,之后拖滑杆一律「先还原 source
* 再按新参数渲染」。否则「马赛克 12px → 40px → 12px」会变成三次采样、块越来
* 越碎且不可逆。历史粒度也因此干净:点效果拍一次快照,拖滑杆不再拍。
*/
'use strict'
import { S } from './state.js'
import { S, runtime } from './state.js'
import { saveSnapshot } from './history.js'
import { createLayerCanvas, getActiveLayer, renderLayerPanel, reorderLayerCanvas, updateLayerCanvasStyles } from './layers.js'
import { layerUnits } from './objects.js'
import { needsPixelSnapshot } from '../vendor/layer-logic.js'
import { toast } from './commands.js'
/** 效果表:label 用于按钮与提示,css 可依赖画布尺寸(柔化半径随图缩放) */
export const QUICK_EFFECTS = {
invert: { label: '反白', hint: '反相:明暗翻转,白底变黑底', css: () => 'invert(1)' },
gray: { label: '灰度', hint: '去色,保留明暗层次', css: () => 'grayscale(1)' },
boost: { label: '增强', hint: '提亮并略加对比', css: () => 'brightness(1.12) contrast(1.1) saturate(1.06)' },
contrast: { label: '高对比', hint: '压成黑白硬调', css: () => 'grayscale(1) contrast(2.4)' },
soft: { label: '柔化', hint: '轻微模糊,弱化背景', css: (c) => 'blur(' + softRadius(c) + 'px)' },
mosaic: { label: '马赛克', hint: '像素化,用于打码', pixel: true }
}
const SOFT_MIN = 0.8
const SOFT_MIN = 1.2
const SOFT_MAX = 8
function softRadius(canvas) {
// 默认半径跟短边走:800px 图 ≈2px(v1.4 是 1.6px,小图上几乎看不出模糊,
// 现在有了滑杆可自己拉,但默认值也要先看得出效果)
const side = Math.min(canvas.width || 0, canvas.height || 0)
return Math.max(SOFT_MIN, Math.min(SOFT_MAX, Math.round(side / 500 * 10) / 10))
return Math.max(SOFT_MIN, Math.min(SOFT_MAX, Math.round(side / 400 * 10) / 10))
}
function mosaicBlock(canvas) {
const side = Math.min(canvas.width || 0, canvas.height || 0)
return Math.max(6, Math.round(side / 60))
}
/**
* 效果表。参数语义分两类:
* unit '%' → 强度 0~100,0 等于不处理(invert/grayscale 原生支持比例)
* unit 'px' → 物理量(马赛克块边长 / 模糊半径),默认值按图短边缩放
* def 是函数:px 类要拿到 canvas 才能算默认值。
*/
export const QUICK_EFFECTS = {
invert: {
label: '反白', hint: '反相:明暗翻转,白底变黑底',
param: '强度', unit: '%', min: 0, max: 100, step: 1, def: () => 100,
render: (canvas, v) => { if (v > 0) filterCanvas(canvas, 'invert(' + (v / 100) + ')') }
},
gray: {
label: '灰度', hint: '去色,保留明暗层次',
param: '强度', unit: '%', min: 0, max: 100, step: 1, def: () => 100,
render: (canvas, v) => { if (v > 0) filterCanvas(canvas, 'grayscale(' + (v / 100) + ')') }
},
boost: {
label: '增强', hint: '提亮并略加对比,适合发灰的截图',
param: '强度', unit: '%', min: 0, max: 100, step: 1, def: () => 100,
render: (canvas, v) => {
if (v <= 0) return
const k = v / 100
filterCanvas(canvas, 'brightness(' + (1 + 0.12 * k).toFixed(3) + ') contrast(' + (1 + 0.1 * k).toFixed(3) + ') saturate(' + (1 + 0.06 * k).toFixed(3) + ')')
}
},
contrast: {
label: '高对比', hint: '压成黑白硬调,突出主体',
param: '强度', unit: '%', min: 0, max: 100, step: 1, def: () => 100,
render: (canvas, v) => {
if (v <= 0) return
const k = v / 100
filterCanvas(canvas, 'grayscale(' + k.toFixed(3) + ') contrast(' + (1 + 1.4 * k).toFixed(3) + ')')
}
},
soft: {
label: '柔化', hint: '模糊,弱化背景',
param: '半径', unit: 'px', min: 0, max: 16, step: 0.5, def: (canvas) => softRadius(canvas),
render: (canvas, v) => { if (v > 0) filterCanvas(canvas, 'blur(' + v + 'px)') }
},
mosaic: {
label: '马赛克', hint: '像素化,用于打码手机号/地址等隐私信息',
param: '块大小', unit: 'px', min: 2, max: 96, step: 1, def: (canvas) => mosaicBlock(canvas),
render: (canvas, v) => { if (v > 1) pixelateCanvas(canvas, v) }
}
}
/** 效果目标:当前活跃位图图层;没有就退回「原图」 */
export function effectTarget() {
const active = getActiveLayer()
@@ -72,8 +116,9 @@ import { toast } from './commands.js'
function pixelateCanvas(canvas, block) {
const w = canvas.width, h = canvas.height
if (!w || !h) return
const sw = Math.max(1, Math.round(w / block))
const sh = Math.max(1, Math.round(h / block))
const b = Math.max(2, block)
const sw = Math.max(1, Math.round(w / b))
const sh = Math.max(1, Math.round(h / b))
const tmp = document.createElement('canvas')
tmp.width = sw
tmp.height = sh
@@ -92,6 +137,16 @@ import { toast } from './commands.js'
ctx.restore()
}
/** 目标层像素的独立副本(同尺寸),作为「可反复重调」的基准 */
function snapshotCanvas(canvas) {
const c = document.createElement('canvas')
c.width = canvas.width
c.height = canvas.height
const ctx = c.getContext('2d')
ctx.drawImage(canvas, 0, 0)
return c
}
/**
* 把「导入图片层」栅格化成普通位图,插在它上面一层。
* 只拷当前 canvas 的可见结果(已含旋转/缩放),所以视觉不变。
@@ -132,7 +187,86 @@ import { toast } from './commands.js'
return clone
}
/** 唯一入口:应用一个快速效果 */
/** 先还原基准像素,再按参数渲染一次 —— 所有重调都走这里 */
function renderFromSource(target, key, value) {
const st = S.fx
const fx = QUICK_EFFECTS[key]
if (!st.source || !fx) return
const ctx = target.canvas.getContext('2d')
ctx.save()
ctx.setTransform(1, 0, 0, 1, 0, 0)
ctx.globalAlpha = 1
ctx.globalCompositeOperation = 'copy'
ctx.filter = 'none'
ctx.imageSmoothingEnabled = true
ctx.drawImage(st.source, 0, 0)
ctx.restore()
fx.render(target.canvas, value)
// 像素变了:包围盒要重算,吸管合成缓存要作废
target._bounds = undefined
S.pickerComposite = null
}
/** 数值展示:px 保留到 0.5(柔化),百分比取整 */
function fmtValue(fx, v) {
if (fx.unit === 'px') return (Math.round(v * 10) / 10) + ' px'
return Math.round(v) + '%'
}
/**
* 刷新侧栏「强度」这一条:滑杆范围随效果切换,目标层对不上时置灰。
* 切图层后源属于旧层,此时拖动会把旧像素写进新层 —— 所以必须靠 layerId 拦住。
* 切回原层自动恢复可用(源还在)。
*/
export function renderFxPanel() {
if (!runtime.el) return
const adv = runtime.el.querySelector('.iwb-editor-fx-adj')
if (!adv) return
const range = adv.querySelector('.iwb-editor-fx-range')
const nameEl = adv.querySelector('.iwb-editor-fx-adj-name')
const valEl = adv.querySelector('.iwb-editor-fx-adj-val')
const targetEl = runtime.el.querySelector('.iwb-editor-fx-target')
const layer = effectTarget()
// 当前生效的效果按钮高亮:面板是静态 DOM,只同步类名,不重建
const activeKey = S.fx.source ? S.fx.key : null
runtime.el.querySelectorAll('[data-fx]').forEach(btn => {
btn.classList.toggle('is-active', Boolean(activeKey) && btn.dataset.fx === activeKey)
})
if (targetEl) {
const name = layer ? layer.name : '无图层'
targetEl.textContent = name
targetEl.title = layer ? '效果作用于「' + name + '」' : '没有可处理的位图图层'
}
const st = S.fx
const fx = st.source ? QUICK_EFFECTS[st.key] : null
if (!fx || !range) {
adv.classList.add('iwb-editor-fx-adj-off')
if (nameEl) nameEl.textContent = '强度'
if (valEl) valEl.textContent = '—'
if (range) { range.disabled = true; range.value = '0' }
return
}
const usable = Boolean(layer && st.layerId === layer.id)
adv.classList.toggle('iwb-editor-fx-adj-off', !usable)
if (nameEl) nameEl.textContent = fx.label + ' · ' + fx.param
range.min = String(fx.min)
range.max = String(fx.max)
range.step = String(fx.step)
range.disabled = !usable
if (usable) range.value = String(st.value)
if (valEl) {
valEl.textContent = fmtValue(fx, st.value)
valEl.title = usable ? '' : '效果作用在「' + (S.layers.find(l => l.id === st.layerId) || {}).name + '」,切回该层可继续调整'
}
}
/** 唯一入口:应用一个效果(同层同效果再点 = 重置回默认参数,不叠加) */
export function applyQuickEffect(key) {
const fx = QUICK_EFFECTS[key]
if (!fx) return false
@@ -143,19 +277,52 @@ import { toast } from './commands.js'
return false
}
saveSnapshot('效果:' + fx.label)
let target = layer
if (!needsPixelSnapshot(layer)) target = rasterizeLayer(layer)
if (!target) { toast('栅格化失败,效果未应用'); return false }
if (fx.pixel) pixelateCanvas(target.canvas, mosaicBlock(target.canvas))
else filterCanvas(target.canvas, fx.css(target.canvas))
const st = S.fx
// 同一层 + 同一效果:用户是在「回默认值」,不是要再糊一层
if (st.source && st.layerId === target.id && st.key === key) {
st.value = fx.def(target.canvas)
renderFromSource(target, key, st.value)
if (S.renderAll) S.renderAll()
toast('「' + fx.label + '」已重置为 ' + fmtValue(fx, st.value), 'success')
return true
}
saveSnapshot('效果:' + fx.label)
// 基准必须是「应用前」的像素:saveSnapshot 只写历史,不改画布,所以这里拍
S.fx = { key, layerId: target.id, source: snapshotCanvas(target.canvas), value: fx.def(target.canvas) }
renderFromSource(target, key, S.fx.value)
target._bounds = undefined
S.pickerComposite = null
if (S.renderAll) S.renderAll()
renderLayerPanel()
toast('已应用「' + fx.label + '」到 ' + target.name + ' · Ctrl+Z 撤销', 'success')
toast('已应用「' + fx.label + '」' + fmtValue(fx, S.fx.value) + ' 到 ' + target.name + ' · 可拖强度微调', 'success')
return true
}
/**
* 拖动强度滑杆。不拍快照(历史粒度 = 一次效果操作),也不重建图层面板
* (拖动中每帧 innerHTML 会闪,缩略图交给松开后的 renderAll 刷新)。
*/
export function setEffectValue(value) {
const st = S.fx
if (!st.source) return false
const fx = QUICK_EFFECTS[st.key]
if (!fx) return false
const target = S.layers.find(l => l.id === st.layerId)
if (!target) return false
const layer = effectTarget()
// 目标层已切换:源像素属于别的层,拒绝写入
if (!layer || layer.id !== st.layerId) return false
const v = Math.min(fx.max, Math.max(fx.min, Number(value) || 0))
st.value = v
renderFromSource(target, st.key, v)
if (runtime.el) {
const valEl = runtime.el.querySelector('.iwb-editor-fx-adj-val')
if (valEl) valEl.textContent = fmtValue(fx, v)
}
return true
}
+23 -6
View File
@@ -8,6 +8,7 @@
import { S, ZOOM_STEP, runtime } from './state.js'
import { ROT_CURSOR, clamp, getPos, isOverRotationHandle, setView, setZoomActual, setZoomFit, zoomStep } from './viewport.js'
import { viewScale } from './scale.js'
import { addBitmapLayer, addBlankLayer, applyBitmapDrag, beginBitmapDrag, clearSelection, deleteLayer, ensureWritableLayer, getActiveCtx, getActiveLayer, hitBitmapHandle, mergeLayers, mergeVisibleLayers, removeVecCanvas, renderLayerPanel } from './layers.js'
import { applyColorChange, beginAltPicker, beginStroke, clearToolRing, drawToolRing, endAltPicker, endStroke, eraseSegment, exitPicker, hidePickerTip, sampleColor, setTool, showPickerTip, strokeSegment } from './tools.js'
import { beginMarquee, updateMarquee, endMarquee, beginLasso, updateLasso, endLasso, clearMarquee, syncAnts, renderSelection } from './selection.js'
@@ -19,7 +20,7 @@ import { cancelImagePlacement, confirmImagePlacement, drawPlacementPreview, hitP
import { close, exportResult } from './index.js'
import { loadImage } from './dom.js'
import { pushHistory, redo, resetDraw, restoreOriginal, restoreAll, saveSnapshot, snapshotState, undo } from './history.js'
import { applyQuickEffect } from './effects.js'
import { applyQuickEffect, setEffectValue } from './effects.js'
import { hexToRgb, parseRatio, rgbToHex } from '../vendor/image-math.js'
@@ -91,7 +92,7 @@ import { hexToRgb, parseRatio, rgbToHex } from '../vendor/image-math.js'
const now = (typeof performance !== 'undefined' && performance.now) ? performance.now() : Date.now()
const last = S.lastClick
const hit = !!last && (now - last.t) < DBL_INTERVAL &&
Math.hypot(pos.x - last.x, pos.y - last.y) < Math.max(8 / S.zoom, 6)
Math.hypot(pos.x - last.x, pos.y - last.y) < Math.max(8 / viewScale(), 6)
S.lastClick = hit ? null : { t: now, x: pos.x, y: pos.y }
return hit
}
@@ -104,7 +105,7 @@ import { hexToRgb, parseRatio, rgbToHex } from '../vendor/image-math.js'
function onCanvasDoubleClick(e, pos) {
const penShape = getPenEditingShape()
if (penShape) {
const pi = hitPenPoint(pos, penShape, Math.max(14 / S.zoom, 8))
const pi = hitPenPoint(pos, penShape, Math.max(14 / viewScale(), 8))
if (pi < 0) return false
e.preventDefault()
saveSnapshot()
@@ -173,7 +174,7 @@ import { hexToRgb, parseRatio, rgbToHex } from '../vendor/image-math.js'
/** 钢笔节点编辑中的按下:点节点拖动/点边插点返回 true(已接管);点空白退出编辑返回 false 继续走工具逻辑 */
function onPenEditMouseDown(e, pos, penShape) {
const pi = hitPenPoint(pos, penShape, Math.max(16 / S.zoom, 9))
const pi = hitPenPoint(pos, penShape, Math.max(16 / viewScale(), 9))
if (pi >= 0) {
S.penDragPt = pi
S.penDragBase = JSON.parse(JSON.stringify(penShape.pts))
@@ -309,7 +310,7 @@ import { hexToRgb, parseRatio, rgbToHex } from '../vendor/image-math.js'
if (!S.penPath) S.penPath = { pts: [], preview: null, closed: false }
const point = { x: clamp(pos.x, 0, S.imgW), y: clamp(pos.y, 0, S.imgH) }
const first = S.penPath.pts[0]
if (first && S.penPath.pts.length >= 3 && Math.hypot(point.x - first.x, point.y - first.y) <= Math.max(12 / S.zoom, S.shapeLineWidth * 1.5)) {
if (first && S.penPath.pts.length >= 3 && Math.hypot(point.x - first.x, point.y - first.y) <= Math.max(12 / viewScale(), S.shapeLineWidth * 1.5)) {
S.penPath.closed = true
S.penPath.nearStart = true
S.penPath.preview = null
@@ -493,7 +494,7 @@ import { hexToRgb, parseRatio, rgbToHex } from '../vendor/image-math.js'
/** 钢笔路径预览:更新悬停点与起点闭合提示 */
function onPenDrawMove(pos) {
if (S.penPath) { S.penPath.preview = pos; const first = S.penPath.pts[0]
const nearStart = first && S.penPath.pts.length >= 3 && Math.hypot(pos.x - first.x, pos.y - first.y) <= Math.max(12 / S.zoom, S.shapeLineWidth * 1.5)
const nearStart = first && S.penPath.pts.length >= 3 && Math.hypot(pos.x - first.x, pos.y - first.y) <= Math.max(12 / viewScale(), S.shapeLineWidth * 1.5)
S.penPath.nearStart = !!nearStart
renderObjects() }
}
@@ -1245,6 +1246,22 @@ import { hexToRgb, parseRatio, rgbToHex } from '../vendor/image-math.js'
})
})
// 快速效果强度滑杆(v1.8):input 只改像素与该行数字 —— 拖动中每帧重建图层面板会闪,
// 缩略图与状态栏交给松开时的 renderAll。用 class 精确匹配,别误伤图层不透明度滑杆。
const fxRangeOf = (e) => (e.target && e.target.closest ? e.target.closest('.iwb-editor-fx-range') : null)
root.addEventListener('input', (e) => {
const range = fxRangeOf(e)
if (!range) return
e.stopPropagation()
setEffectValue(parseFloat(range.value))
})
root.addEventListener('change', (e) => {
const range = fxRangeOf(e)
if (!range) return
e.stopPropagation()
if (S.renderAll) S.renderAll()
})
const body = root.querySelector('.iwb-editor-optionbar-body')
if (body) {
body.addEventListener('mousedown', (e) => e.stopPropagation())
+41 -3
View File
@@ -32,9 +32,11 @@ import { clearSelection, purgeVectorCanvases, renderLayerPanel } from './layers.
import { createEl, loadImage } from './dom.js'
import { renderObjects, hideTextInput } from './objects.js'
import { setupCanvas } from './viewport.js'
import { resetOverlayTransform } from './scale.js'
import { updateAllUI, bindLiteUI, renderOptionBar, updateStatusbar } from './events.js'
import { disposeSelection, renderSelection, selectionInfo, syncAnts, registerSelectionCommands } from './selection.js'
import { bindFloating, positionFloating, hideSelectionContext } from './floating.js'
import { renderFxPanel } from './effects.js'
import { loadExportOptions, prepareOutput, downloadBlob, bindExportUI, renderExportUI } from './export.js'
import { toast } from './commands.js'
@@ -46,6 +48,7 @@ import { toast } from './commands.js'
// 命令层 / 蚂蚁线的渲染出口走注入,避免新模块与 events.js 形成顶层求值循环
S.renderAll = renderAll
S.positionFloating = positionFloating
S.renderFxPanel = renderFxPanel
try {
const img = await loadImage(options.imageBase64)
@@ -119,6 +122,8 @@ import { toast } from './commands.js'
S.lastClick = null
S.lastNameClick = null
S.altPicker = false
// 快速效果的基准像素属于上一张图,重开必须清掉(否则滑杆会往新图上写旧像素)
S.fx = { key: null, value: 0, layerId: null, source: null }
S.zCounter = Math.max(S.layers.length - 1, 0)
S.placingImage = null
S.placingHandle = null
@@ -135,10 +140,9 @@ import { toast } from './commands.js'
hideSelectionContext()
if (S.selectionCtx) renderSelection()
if (S.cursorCtx) {
const pad = S.overlayPad || 0
S.cursorCtx.setTransform(1, 0, 0, 1, 0, 0)
S.cursorCtx.clearRect(0, 0, S.imgW + pad * 2, S.imgH + pad * 2)
S.cursorCtx.setTransform(1, 0, 0, 1, pad, pad)
S.cursorCtx.clearRect(0, 0, S.cursorCtx.canvas.width, S.cursorCtx.canvas.height)
resetOverlayTransform(S.cursorCtx)
}
}
@@ -147,6 +151,7 @@ import { toast } from './commands.js'
if (!S.open || !runtime.el) return
renderObjects()
renderLayerPanel()
renderFxPanel()
renderOptionBar()
updateStatusbar()
renderExportUI()
@@ -209,6 +214,8 @@ import { toast } from './commands.js'
// 2) 原图引用与吸管合成缓存(各为一张全幅位图)
S.originalImage = null
S.pickerComposite = null
// 2b) 快速效果的基准像素:又一张全幅位图,不释放就白占一份图大小的内存
S.fx = { key: null, value: 0, layerId: null, source: null }
// 3) 交互态复位:关闭后 window mouseup 等全局监听仍活着,靠标志位保证不落到绘制路径
S.isDrawing = false
S.panning = false
@@ -324,9 +331,40 @@ import { toast } from './commands.js'
redo: S.redoStack.length,
exportOptions: S.exportOptions ? { ...S.exportOptions } : null,
lastExport: S.lastExport ? { ...S.lastExport } : null,
// 快速效果的可重调状态:hasSource=false 表示还没点过效果(滑杆应置灰)
fx: { key: S.fx.key, value: S.fx.value, layerId: S.fx.layerId, hasSource: Boolean(S.fx.source) },
interaction: S.interaction,
ants: !!S._antFrame,
view: S.viewX !== null ? [Math.round(S.viewX), Math.round(S.viewY)] : null,
// 图层整幅像素指纹(抽样校验和):断言「改强度后从基准重算」而不是叠加,
// 比逐点采样稳 —— 马赛克/模糊的差异散在整幅,单点可能刚好相同
layerHash: (id) => {
const l = S.layers.find(v => v.id === id)
if (!l || !l.ctx || !l.canvas) return 0
try {
const d = l.ctx.getImageData(0, 0, l.canvas.width, l.canvas.height).data
let h = 2166136261
for (let i = 0; i < d.length; i += 97) {
h ^= d[i]
h = Math.imul(h, 16777619)
}
return h >>> 0
} catch (e) { return 0 }
},
// 非透明像素的平均色:断言效果是否落在预期值上(如反相 50% 必然趋近 128)
avgColor: (id) => {
const l = S.layers.find(v => v.id === id)
if (!l || !l.ctx || !l.canvas) return null
try {
const d = l.ctx.getImageData(0, 0, l.canvas.width, l.canvas.height).data
let r = 0, g = 0, b = 0, n = 0
for (let i = 0; i < d.length; i += 4) {
if (d[i + 3] < 200) continue
r += d[i]; g += d[i + 1]; b += d[i + 2]; n++
}
return n ? [Math.round(r / n), Math.round(g / n), Math.round(b / n), n] : null
} catch (e) { return null }
},
pixel: (id, x, y) => {
const l = S.layers.find(v => v.id === id)
if (!l || !l.ctx) return null
+9 -4
View File
@@ -10,6 +10,7 @@
import { S, runtime } from './state.js'
import { TEXT_FONT, allObjects, assignLayerZ, deleteSelectedShape, deleteSelectedText, layerUnits, layerUnitsDesc, renderObjects, selectUnit, sortLayersByZ, textBounds } from './objects.js'
import { boxCorners, clamp, drawRotationHandles, hitRotationHandle, rotPt, unrotPt } from './viewport.js'
import { viewScale } from './scale.js'
import { drawShape } from './tools.js'
import { saveSnapshot, snapshotState } from './history.js'
import { placeImageDirectly } from './placement.js'
@@ -115,7 +116,7 @@ import { isDrawableLayer } from '../vendor/layer-logic.js'
const rot = layer.rotation || 0
const cx = box.x + box.w / 2, cy = box.y + box.h / 2
const lp = unrotPt(pos.x, pos.y, cx, cy, rot)
const R = 14 / S.zoom
const R = 14 / viewScale()
if (hitRotationHandle(lp, box)) return 'rotate'
const points = {
nw: [box.x, box.y], ne: [box.x + box.w, box.y],
@@ -201,11 +202,11 @@ import { isDrawableLayer } from '../vendor/layer-logic.js'
if (!(box.w > 0 && box.h > 0)) return
const ctx = S.overlayCtx
const rot = layer.rotation || 0
const hs = 5.5 / S.zoom
const hs = 5.5 / viewScale()
ctx.save()
ctx.strokeStyle = '#e8a735'
ctx.lineWidth = 1.5 / S.zoom
ctx.setLineDash([6 / S.zoom, 3 / S.zoom])
ctx.lineWidth = 1.5 / viewScale()
ctx.setLineDash([6 / viewScale(), 3 / viewScale()])
const corners = boxCorners(box.x, box.y, box.w, box.h, rot)
ctx.beginPath()
ctx.moveTo(corners[0][0], corners[0][1])
@@ -317,6 +318,10 @@ export function setActiveLayer(id) {
if (!changed) return
renderLayerPanel()
renderObjects()
// 效果参数滑杆绑的是「上次点效果的那个层」:切层后必须立刻置灰/恢复,
// 否则用户会在新层上拖出一个属于旧层的像素结果(v1.8)。
// 走注入而不是直接 import effects.js —— 后者已经 import 本模块,硬连会成环。
if (S.renderFxPanel) S.renderFxPanel()
}
/** 添加位图图层(导入图片)— 便利版:一步落层,不再需要 Enter 二次确认
+24 -22
View File
@@ -8,6 +8,7 @@
import { S, runtime } from './state.js'
import { boxCorners, clamp, drawRotationHandles, hitRotationHandle, rotPt, unrotPt } from './viewport.js'
import { viewScale } from './scale.js'
import { clearOverlay, drawCropPreview } from './crop.js'
import { drawBitmapSelection, drawVectorToCanvas, hitBitmapAt, removeVecCanvas, renderLayerPanel, reorderLayerCanvas } from './layers.js'
import { drawPlacementPreview } from './placement.js'
@@ -67,7 +68,7 @@ import { isDrawableLayer } from '../vendor/layer-logic.js'
const lp = rot ? unrotPt(pos.x, pos.y, b.x + b.w / 2, b.y + b.h / 2, rot) : [pos.x, pos.y]
if (hitRotationHandle(lp, b)) return 'rotate'
const local = { nw: [b.x, b.y], ne: [b.x + b.w, b.y], sw: [b.x, b.y + b.h], se: [b.x + b.w, b.y + b.h] }
const R = 12 / S.zoom
const R = 12 / viewScale()
let best = null, bestDist = 1e9
for (const name in local) {
const dx = lp[0] - local[name][0], dy = lp[1] - local[name][1]
@@ -103,7 +104,7 @@ import { isDrawableLayer } from '../vendor/layer-logic.js'
const lp = unrotPt(pos.x, pos.y, b.x + b.w / 2, b.y + b.h / 2, s.rotation)
pos = { x: lp[0], y: lp[1] }
}
if (s.type === 'pen') { const pts = s.pts || []; for (let i = 1; i < pts.length; i++) if (distToSeg(pos.x, pos.y, pts[i-1].x, pts[i-1].y, pts[i].x, pts[i].y) <= Math.max(8 / S.zoom, s.lw)) return true; if (s.closed && pts.length > 2 && distToSeg(pos.x, pos.y, pts[pts.length-1].x, pts[pts.length-1].y, pts[0].x, pts[0].y) <= Math.max(8 / S.zoom, s.lw)) return true; if (!includeInterior) return false; const b = shapeBounds(s); return pos.x >= b.x && pos.x <= b.x + b.w && pos.y >= b.y && pos.y <= b.y + b.h }
if (s.type === 'pen') { const pts = s.pts || []; for (let i = 1; i < pts.length; i++) if (distToSeg(pos.x, pos.y, pts[i-1].x, pts[i-1].y, pts[i].x, pts[i].y) <= Math.max(8 / viewScale(), s.lw)) return true; if (s.closed && pts.length > 2 && distToSeg(pos.x, pos.y, pts[pts.length-1].x, pts[pts.length-1].y, pts[0].x, pts[0].y) <= Math.max(8 / viewScale(), s.lw)) return true; if (!includeInterior) return false; const b = shapeBounds(s); return pos.x >= b.x && pos.x <= b.x + b.w && pos.y >= b.y && pos.y <= b.y + b.h }
if (s.type === 'circle') {
const b = shapeBounds(s)
const cx = b.x + b.w / 2, cy = b.y + b.h / 2
@@ -111,7 +112,7 @@ import { isDrawableLayer } from '../vendor/layer-logic.js'
const nx = (pos.x - cx) / rx, ny = (pos.y - cy) / ry
const value = nx * nx + ny * ny
if (includeInterior || s.fill) return value <= 1
const edgeTolerance = Math.max(4 / S.zoom, s.lw / Math.min(rx, ry))
const edgeTolerance = Math.max(4 / viewScale(), s.lw / Math.min(rx, ry))
const outer = (1 + edgeTolerance) * (1 + edgeTolerance)
const inner = Math.max(0, 1 - edgeTolerance) * Math.max(0, 1 - edgeTolerance)
return value >= inner && value <= outer
@@ -127,7 +128,7 @@ import { isDrawableLayer } from '../vendor/layer-logic.js'
pos.y >= b.y + pad && pos.y <= b.y + b.h - pad
return !inInner
}
return distToSeg(pos.x, pos.y, s.x1, s.y1, s.x2, s.y2) <= Math.max(8 / S.zoom, s.lw)
return distToSeg(pos.x, pos.y, s.x1, s.y1, s.x2, s.y2) <= Math.max(8 / viewScale(), s.lw)
}
export function hitShapeLayer(pos, includeInterior) {
@@ -310,8 +311,8 @@ import { isDrawableLayer } from '../vendor/layer-logic.js'
const lp = rot ? unrotPt(pos.x, pos.y, cx, cy, rot) : [pos.x, pos.y]
if (hitRotationHandle(lp, b)) return 'rotate'
const pts = shapeHandlePoints(s)
const offset = 8 / S.zoom
const R = Math.max(14 / S.zoom, 9)
const offset = 8 / viewScale()
const R = 14 / viewScale()
let best = null, bestDist = 1e9
for (const name in pts) {
const px = pts[name][0] + (name.includes('w') ? -offset : name.includes('e') ? offset : 0)
@@ -352,7 +353,7 @@ import { isDrawableLayer } from '../vendor/layer-logic.js'
return
}
const b = shapeBounds(s)
const offset = 8 / S.zoom
const offset = 8 / viewScale()
const adjusted = { x: pos.x - (handle.includes('w') ? -offset : handle.includes('e') ? offset : 0), y: pos.y - (handle.includes('n') ? -offset : handle.includes('s') ? offset : 0) }
let x1 = b.x, y1 = b.y, x2 = b.x + b.w, y2 = b.y + b.h
if (handle.includes('e')) x2 = Math.max(x1 + 2, adjusted.x)
@@ -368,13 +369,14 @@ import { isDrawableLayer } from '../vendor/layer-logic.js'
const ctx = S.overlayCtx
const pts = path.pts.slice()
const first = pts[0]
const nearStart = path.preview && pts.length >= 3 && Math.hypot(path.preview.x - first.x, path.preview.y - first.y) <= Math.max(12 / S.zoom, S.shapeLineWidth * 1.5)
const nearStart = path.preview && pts.length >= 3 && Math.hypot(path.preview.x - first.x, path.preview.y - first.y) <= Math.max(12 / viewScale(), S.shapeLineWidth * 1.5)
if (path.preview) pts.push(nearStart ? first : path.preview)
ctx.save()
ctx.strokeStyle = S.color
ctx.fillStyle = nearStart ? 'rgba(232, 167, 53, 0.18)' : 'transparent'
ctx.lineWidth = Math.max(1, S.shapeLineWidth) / S.zoom
ctx.setLineDash([8 / S.zoom, 5 / S.zoom])
// 预览线宽 = 实际线宽(图片单位),不再除缩放,做到所见即所得
ctx.lineWidth = Math.max(1, S.shapeLineWidth)
ctx.setLineDash([8 / viewScale(), 5 / viewScale()])
ctx.beginPath()
ctx.moveTo(pts[0].x, pts[0].y)
for (let i = 1; i < pts.length; i++) ctx.lineTo(pts[i].x, pts[i].y)
@@ -386,7 +388,7 @@ import { isDrawableLayer } from '../vendor/layer-logic.js'
ctx.beginPath()
ctx.fillStyle = i === 0 && nearStart ? '#e8a735' : '#ffffff'
ctx.strokeStyle = S.color
ctx.arc(point.x, point.y, Math.max(4, 6 / S.zoom), 0, Math.PI * 2)
ctx.arc(point.x, point.y, 6 / viewScale(), 0, Math.PI * 2)
ctx.fill(); ctx.stroke()
}
ctx.restore()
@@ -398,8 +400,8 @@ import { isDrawableLayer } from '../vendor/layer-logic.js'
const rot = s.rotation || 0
octx.save()
octx.strokeStyle = '#e8a735'
octx.lineWidth = 1.5 / S.zoom
octx.setLineDash([6 / S.zoom, 3 / S.zoom])
octx.lineWidth = 1.5 / viewScale()
octx.setLineDash([6 / viewScale(), 3 / viewScale()])
const corners = boxCorners(b.x, b.y, b.w, b.h, rot)
octx.beginPath()
octx.moveTo(corners[0][0], corners[0][1])
@@ -407,7 +409,7 @@ import { isDrawableLayer } from '../vendor/layer-logic.js'
octx.closePath()
octx.stroke()
octx.setLineDash([])
const hs = 5.5 / S.zoom
const hs = 5.5 / viewScale()
octx.fillStyle = '#ffffff'
octx.strokeStyle = '#e8a735'
const pts = shapeHandleWorld(s)
@@ -453,16 +455,16 @@ import { isDrawableLayer } from '../vendor/layer-logic.js'
const octx = S.overlayCtx
octx.save()
octx.strokeStyle = '#e8a735'
octx.lineWidth = 1.5 / S.zoom
octx.setLineDash([6 / S.zoom, 3 / S.zoom])
const corners = boxCorners(b.x - 2 / S.zoom, b.y - 2 / S.zoom, b.w + 4 / S.zoom, b.h + 4 / S.zoom, rot)
octx.lineWidth = 1.5 / viewScale()
octx.setLineDash([6 / viewScale(), 3 / viewScale()])
const corners = boxCorners(b.x - 2 / viewScale(), b.y - 2 / viewScale(), b.w + 4 / viewScale(), b.h + 4 / viewScale(), rot)
octx.beginPath()
octx.moveTo(corners[0][0], corners[0][1])
for (let i = 1; i < corners.length; i++) octx.lineTo(corners[i][0], corners[i][1])
octx.closePath()
octx.stroke()
octx.setLineDash([])
const hs = 5.5 / S.zoom
const hs = 5.5 / viewScale()
octx.fillStyle = '#ffffff'
octx.strokeStyle = '#e8a735'
const pts = textHandlePoints(sel)
@@ -522,7 +524,7 @@ import { isDrawableLayer } from '../vendor/layer-logic.js'
const pts = shape.pts || []
const b = shapeBounds(shape)
const lp = shape.rotation ? unrotPt(pos.x, pos.y, b.x + b.w / 2, b.y + b.h / 2, shape.rotation) : [pos.x, pos.y]
const r = Math.max(12 / S.zoom, 6)
const r = 12 / viewScale()
for (let i = 0; i < pts.length - 1; i++) {
if (distToSeg(lp[0], lp[1], pts[i].x, pts[i].y, pts[i + 1].x, pts[i + 1].y) <= r) return i
}
@@ -539,9 +541,9 @@ import { isDrawableLayer } from '../vendor/layer-logic.js'
const rot = shape.rotation || 0
const cx = b.x + b.w / 2, cy = b.y + b.h / 2
const W = (p) => rotPt(p.x, p.y, cx, cy, rot)
const R = Math.max(7 / S.zoom, 5)
const R = 7 / viewScale()
ctx.save()
ctx.lineWidth = 1.5 / S.zoom
ctx.lineWidth = 1.5 / viewScale()
const segments = []
for (let i = 0; i < pts.length - 1; i++) segments.push([pts[i], pts[i + 1]])
if (shape.closed && pts.length >= 3) segments.push([pts[pts.length - 1], pts[0]])
@@ -550,7 +552,7 @@ import { isDrawableLayer } from '../vendor/layer-logic.js'
const wa = W(a), wb = W(bb)
const mx = (wa[0] + wb[0]) / 2, my = (wa[1] + wb[1]) / 2
ctx.beginPath()
ctx.arc(mx, my, Math.max(3 / S.zoom, 2), 0, Math.PI * 2)
ctx.arc(mx, my, 3 / viewScale(), 0, Math.PI * 2)
ctx.stroke()
}
for (let i = 0; i < pts.length; i++) {
+10 -9
View File
@@ -8,6 +8,7 @@
import { S } from './state.js'
import { boxCorners, drawRotationHandles, hitRotationHandle, rotPt, unrotPt } from './viewport.js'
import { viewScale } from './scale.js'
import { clearOverlay } from './crop.js'
import { createLayerCanvas, redrawBitmapLayer, renderLayerPanel, reorderLayerCanvas, setActiveLayer, updateLayerCanvasStyles } from './layers.js'
import { saveSnapshot } from './history.js'
@@ -131,8 +132,8 @@ import { updateCursor } from './events.js'
const corners = boxCorners(x, y, w, h, rot)
ctx.save()
ctx.strokeStyle = '#4488ff'
ctx.lineWidth = 2 / S.zoom
ctx.setLineDash([8 / S.zoom, 4 / S.zoom])
ctx.lineWidth = 2 / viewScale()
ctx.setLineDash([8 / viewScale(), 4 / viewScale()])
ctx.beginPath()
ctx.moveTo(corners[0][0], corners[0][1])
for (let i = 1; i < corners.length; i++) ctx.lineTo(corners[i][0], corners[i][1])
@@ -140,10 +141,10 @@ import { updateCursor } from './events.js'
ctx.stroke()
ctx.setLineDash([])
// 8 个缩放手柄(旋转后位置)
const hs = 5.5 / S.zoom
const hs = 5.5 / viewScale()
ctx.fillStyle = '#fff'
ctx.strokeStyle = '#4488ff'
ctx.lineWidth = 1.5 / S.zoom
ctx.lineWidth = 1.5 / viewScale()
const localPts = {
nw: [x, y], ne: [x + w, y],
sw: [x, y + h], se: [x + w, y + h],
@@ -162,17 +163,17 @@ import { updateCursor } from './events.js'
drawRotationHandles(ctx, { x, y, w, h }, rot)
// 提示文字
ctx.save()
ctx.font = 'bold ' + Math.round(14 / S.zoom) + 'px sans-serif'
ctx.font = 'bold ' + Math.round(14 / viewScale()) + 'px sans-serif'
ctx.textAlign = 'center'
ctx.textBaseline = 'top'
const hintText = '拖拽手柄调整大小 · 圆点=旋转 · Shift=等比/15°吸附 · Enter=确认 · Esc=取消'
const br = boxCorners(x, y, w, h, rot).reduce((acc, pt) => Math.max(acc, pt[1]), -Infinity)
const hintY = br + 10 / S.zoom
const hintY = br + 10 / viewScale()
const tw = ctx.measureText(hintText).width
ctx.fillStyle = 'rgba(0,0,0,0.6)'
ctx.fillRect(cx - tw / 2 - 6 / S.zoom, hintY, tw + 12 / S.zoom, 22 / S.zoom)
ctx.fillRect(cx - tw / 2 - 6 / viewScale(), hintY, tw + 12 / viewScale(), 22 / viewScale())
ctx.fillStyle = 'rgba(255,255,255,0.95)'
ctx.fillText(hintText, cx, hintY + 4 / S.zoom)
ctx.fillText(hintText, cx, hintY + 4 / viewScale())
ctx.restore()
}
@@ -182,7 +183,7 @@ import { updateCursor } from './events.js'
const rot = S.placingImage.rotation || 0
const cx = x + w / 2, cy = y + h / 2
const lp = unrotPt(pos.x, pos.y, cx, cy, rot)
const R = 12 / S.zoom
const R = 12 / viewScale()
// 四角外侧圆弧 = 旋转手柄
if (hitRotationHandle(lp, { x, y, w, h })) return 'rotate'
const pts = {
+49
View File
@@ -0,0 +1,49 @@
/* scale.js - 视图缩放换算(零依赖叶子模块,只读 S)
*
* 为什么单独成文件:这三个函数被 viewport / objects / layers / crop / selection /
* placement / events 共用,而 viewport 与 crop、objects、layers 之间存在**循环 import**。
* 把换算函数放在有循环的模块里,esbuild 打成 IIFE 后另一侧会拿到 undefined:
* 实测 clearOverlay 报 "resetOverlayTransform is not defined"(setupCanvas 调 clearOverlay,
* 此时 viewport 模块尚在求值中)。叶子模块没有反向依赖,任何时候都可用。
*/
'use strict'
import { S } from './state.js'
/**
* 视图缩放:**1 个图片像素 = 多少屏幕 CSS 像素**。
*
* ⚠️ 这不是 S.zoom。S.zoom 是「相对 fitW 的倍数」:图片适应窗口后 fitW ≠ imgW,
* 所以 zoom=1 时屏幕上每个图片像素只占 fitW/imgW 个 CSS 像素。
*
* 所有「屏幕上恒定大小」的界面元素(控制点、描边粗细、虚线间距、命中半径、
* 预览文字)都必须用 X / viewScale() 换算。直接写 X / S.zoom 会让实际屏幕尺寸
* 变成 X * fitW / imgW —— 只跟图片尺寸走、和缩放无关:
* 小图被放大铺满容器时 fitW/imgW 可达 4~8,控制点就会大得离谱;大图则缩成看不见。
*/
export function viewScale() {
return (S.imgW && S.fitW) ? (S.fitW * S.zoom) / S.imgW : 1
}
/**
* overlay 系列画布(选中框 / 蚂蚁线 / 笔刷环)的像素倍率。
*
* 这三张画布的像素缓冲原本就等于「图片尺寸 + padding」,CSS 再按 viewScale 拉伸显示。
* 小图被「适应窗口」放大 5~10 倍时缓冲严重不足,控制点、虚线全糊成一团发光点。
*
* 倍率只看适应窗口的基准比例(fitW / imgW,**不含 zoom**):拖动缩放不会改变它,
* 所以不会在缩放过程中反复重建 canvas。上限 4 是为内存 —— 缓冲面积按平方增长。
*/
export function overlayScale() {
const base = (S.imgW && S.fitW) ? S.fitW / S.imgW : 1
return Math.max(1, Math.min(4, base))
}
/** 把 ctx 重置到「图片坐标」基准:含 pad 偏移与 overlayScale 倍率。
* 清屏后必须用它恢复,否则后续绘制会按 1:1 铺到设备像素上、整体偏移。 */
export function resetOverlayTransform(cx) {
const k = overlayScale()
const pad = S.overlayPad || 0
cx.setTransform(k, 0, 0, k, pad * k, pad * k)
}
+6 -7
View File
@@ -13,6 +13,7 @@
import { S } from './state.js'
import { clamp, getPos } from './viewport.js'
import { resetOverlayTransform, viewScale } from './scale.js'
import { clearOverlay } from './crop.js'
import { defineCommand, runCommand, toast } from './commands.js'
import { createLayerCanvas, ensureWritableLayer, getActiveLayer, reorderLayerCanvas, setActiveLayer, updateLayerCanvasStyles } from './layers.js'
@@ -32,23 +33,21 @@ import { createLayerCanvas, ensureWritableLayer, getActiveLayer, reorderLayerCan
function clearSelectionCanvas() {
const ctx = S.selectionCtx
if (!ctx) return
const pad = S.overlayPad || 0
ctx.save()
ctx.setTransform(1, 0, 0, 1, 0, 0)
ctx.clearRect(0, 0, S.imgW + pad * 2, S.imgH + pad * 2)
ctx.clearRect(0, 0, ctx.canvas.width, ctx.canvas.height)
ctx.restore()
ctx.setTransform(1, 0, 0, 1, pad, pad)
resetOverlayTransform(ctx)
}
export function clearCursorCanvas() {
const ctx = S.cursorCtx
if (!ctx) return
const pad = S.overlayPad || 0
ctx.save()
ctx.setTransform(1, 0, 0, 1, 0, 0)
ctx.clearRect(0, 0, S.imgW + pad * 2, S.imgH + pad * 2)
ctx.clearRect(0, 0, ctx.canvas.width, ctx.canvas.height)
ctx.restore()
ctx.setTransform(1, 0, 0, 1, pad, pad)
resetOverlayTransform(ctx)
}
/** 蚂蚁线:黑白两段错位的虚线,rAF 只重绘这一张小画布 */
@@ -56,7 +55,7 @@ import { createLayerCanvas, ensureWritableLayer, getActiveLayer, reorderLayerCan
if (!S.selectionCtx) return
clearSelectionCanvas()
const ctx = S.selectionCtx
const k = 1 / Math.max(S.zoom, 0.0001)
const k = 1 / Math.max(viewScale(), 0.0001)
// 拉框 / 套索过程中:画预览,不画正式选区
if (S.marquee || (S.lassoPts && S.lassoPts.length > 1)) {
+4
View File
@@ -29,6 +29,10 @@
lastNameClick: null,
altPicker: false, // 按住 Alt 的临时吸管(画笔/橡皮下),松开 Alt 回到原工具
pickerComposite: null, // 吸管取样用的合成画布缓存(切工具/画布变化时失效)
// v1.8 快速效果的「可重调」状态:source 是点效果那一刻的像素备份,
// 拖强度滑杆时一律从 source 重算,绝不在上一次结果上叠加(否则来回拖会越拖越糊)。
// layerId 用于判断源是否还对得上当前目标层:切层后滑杆自动置灰,切回即恢复。
fx: { key: null, value: 0, layerId: null, source: null },
rectFill: false, // 矩形/圆形是否实心填充
penFill: true, // 钢笔闭合路径是否实心填充(只对闭合路径有意义)
// v1.2 工具参数解耦:形状线宽与文字字号不再借用画笔粗细,
+3 -3
View File
@@ -12,6 +12,7 @@ import { commitTextInput, getSelectedShape, getSelectedText, layerUnits, renderO
import { cancelCrop, clearOverlay, hideCropBar, showCropBar, updateCropInfo } from './crop.js'
import { cancelImagePlacement } from './placement.js'
import { clamp } from './viewport.js'
import { resetOverlayTransform } from './scale.js'
import { getActiveCtx, getActiveLayer, renderLayerPanel } from './layers.js'
import { saveSnapshot } from './history.js'
import { updateBrushParamUI, updateColorUI, updateToolUI } from './events.js'
@@ -222,12 +223,11 @@ import { hexToRgb, rgbToHex } from '../vendor/image-math.js'
export function clearToolRing() {
const ctx = S.cursorCtx
if (!ctx) return
const pad = S.overlayPad || 0
ctx.save()
ctx.setTransform(1, 0, 0, 1, 0, 0)
ctx.clearRect(0, 0, S.imgW + pad * 2, S.imgH + pad * 2)
ctx.clearRect(0, 0, ctx.canvas.width, ctx.canvas.height)
ctx.restore()
ctx.setTransform(1, 0, 0, 1, pad, pad)
resetOverlayTransform(ctx)
}
/** 圆形笔刷光标:画在独立 cursorCanvas,避免 clearOverlay() 擦掉其它交互层 */
+32 -13
View File
@@ -7,6 +7,7 @@
'use strict'
import { S, ZOOM_MAX, ZOOM_MIN } from './state.js'
import { overlayScale, resetOverlayTransform, viewScale } from './scale.js'
import { bindCanvasEvents, updateZoomUI } from './events.js'
import { clearOverlay } from './crop.js'
import { createLayerCanvas, purgeVectorCanvases, renderLayerPanel, styleVectorViewport } from './layers.js'
@@ -46,11 +47,14 @@ import { getSelectedShape, getSelectedText, renderObjects, shapeBounds, textBoun
S.strokeCanvas.style.display = 'none'
// 裁剪越界区域属于交互工作区,不改变图片本身的画布尺寸。
S.overlayPad = Math.max(96, Math.ceil(Math.max(S.imgW, S.imgH) * 0.18))
// overlayScale 依赖 fitW,必须先算出适应尺寸再建交互层缓冲
computeFit()
const uiK = overlayScale()
for (const [c, cx] of [[S.overlayCanvas, S.overlayCtx], [S.selectionCanvas, S.selectionCtx], [S.cursorCanvas, S.cursorCtx]]) {
if (!c || !cx) continue
c.width = S.imgW + S.overlayPad * 2
c.height = S.imgH + S.overlayPad * 2
cx.setTransform(1, 0, 0, 1, S.overlayPad, S.overlayPad)
c.width = Math.round((S.imgW + S.overlayPad * 2) * uiK)
c.height = Math.round((S.imgH + S.overlayPad * 2) * uiK)
resetOverlayTransform(cx)
}
// 创建图层 1: 原图
@@ -82,7 +86,6 @@ import { getSelectedShape, getSelectedText, renderObjects, shapeBounds, textBoun
renderObjects()
computeFit()
S.viewX = null
applyView()
renderLayerPanel()
@@ -108,11 +111,13 @@ import { getSelectedShape, getSelectedText, renderObjects, shapeBounds, textBoun
S.strokeCanvas.width = S.imgW
S.strokeCanvas.height = S.imgH
S.overlayPad = Math.max(96, Math.ceil(Math.max(S.imgW, S.imgH) * 0.18))
computeFit()
const uiK = overlayScale()
for (const [c, cx] of [[S.overlayCanvas, S.overlayCtx], [S.selectionCanvas, S.selectionCtx], [S.cursorCanvas, S.cursorCtx]]) {
if (!c || !cx) continue
c.width = S.imgW + S.overlayPad * 2
c.height = S.imgH + S.overlayPad * 2
cx.setTransform(1, 0, 0, 1, S.overlayPad, S.overlayPad)
c.width = Math.round((S.imgW + S.overlayPad * 2) * uiK)
c.height = Math.round((S.imgH + S.overlayPad * 2) * uiK)
resetOverlayTransform(cx)
}
purgeVectorCanvases()
@@ -124,7 +129,6 @@ import { getSelectedShape, getSelectedText, renderObjects, shapeBounds, textBoun
S.pickerComposite = null
clearOverlay()
computeFit()
S.viewX = null
applyView()
renderObjects()
@@ -238,6 +242,18 @@ import { getSelectedShape, getSelectedText, renderObjects, shapeBounds, textBoun
export function clamp(v, min, max) { return Math.max(min, Math.min(max, v)) }
/**
* 视图缩放:**1 个图片像素 = 多少屏幕 CSS 像素**。
*
* ⚠️ 这不是 S.zoom。S.zoom 是「相对 fitW 的倍数」:图片适应窗口后 fitW ≠ imgW,
* 所以 zoom=1 时屏幕上每个图片像素只占 fitW/imgW 个 CSS 像素。
*
* 所有「屏幕上恒定大小」的界面元素(控制点、描边粗细、虚线间距、命中半径、
* 预览文字)都必须用 X / viewScale() 换算。直接写 X / S.zoom 会让实际屏幕尺寸
* 变成 X * fitW / imgW —— 只跟图片尺寸走、和缩放无关:
* 小图被放大铺满容器时 fitW/imgW 可达 4~8,控制点就会大得离谱;大图则缩成看不见。
*/
// ============ 旋转辅助 ============
export function rotPt(px, py, cx, cy, deg) {
if (!deg) return [px, py]
@@ -251,7 +267,8 @@ import { getSelectedShape, getSelectedText, renderObjects, shapeBounds, textBoun
/** 旋转手柄:四个角沿对角线向外偏移(局部坐标) */
function rotationHandlesLocal(b) {
const cx = b.x + b.w / 2, cy = b.y + b.h / 2
const d = 26 / Math.max(S.zoom, 0.0001)
// 26 屏幕像素的间距,换算成图片单位(不能除以 S.zoom,否则随图片尺寸漂移)
const d = 26 / Math.max(viewScale(), 0.0001)
return [[b.x, b.y], [b.x + b.w, b.y], [b.x + b.w, b.y + b.h], [b.x, b.y + b.h]].map(c => {
const dx = c[0] - cx, dy = c[1] - cy, len = Math.hypot(dx, dy) || 1
return [c[0] + dx / len * d, c[1] + dy / len * d]
@@ -260,7 +277,9 @@ import { getSelectedShape, getSelectedText, renderObjects, shapeBounds, textBoun
/** 命中旋转手柄(传局部坐标点) */
export function hitRotationHandle(lp, b) {
const pts = rotationHandlesLocal(b)
const R = Math.max(11 / Math.max(S.zoom, 0.0001), 8)
// 11 屏幕像素的命中半径。原先用 Math.max(..., 8) 托底,但托底值是图片单位,
// 放大显示时会变成巨大的屏幕命中区(误触),故只按 viewScale 换算。
const R = 11 / Math.max(viewScale(), 0.0001)
for (const pt of pts) {
if (Math.hypot(lp[0] - pt[0], lp[1] - pt[1]) < R) return true
}
@@ -270,10 +289,10 @@ import { getSelectedShape, getSelectedText, renderObjects, shapeBounds, textBoun
export function drawRotationHandles(ctx, b, rot) {
const cx = b.x + b.w / 2, cy = b.y + b.h / 2
const pts = rotationHandlesLocal(b)
const k = Math.max(S.zoom, 0.0001)
const r = Math.max(6.5 / k, 5)
const k = Math.max(viewScale(), 0.0001)
const r = 6.5 / k
const lw = 1.5 / k
const ah = Math.max(3 / k, 2.6) // 箭头长度
const ah = 3 / k // 箭头长度
const A0 = Math.PI * 0.2, A1 = Math.PI * 1.72
ctx.save()
ctx.strokeStyle = '#f0b34e'
+349 -97
View File
@@ -9,7 +9,7 @@
var __IWB_ANNOTATE_MANIFEST__ = {
id: 'image-annotate',
name: '标注 / 修图',
version: '1.7.0',
version: '1.8.2',
apiVersion: 1,
capabilities: ['commands', 'nodeActions', 'canvas', 'canvasWrite'],
settings: {
@@ -51,6 +51,10 @@ var __IWB_ANNOTATE_MANIFEST__ = {
// 按住 Alt 的临时吸管(画笔/橡皮下),松开 Alt 回到原工具
pickerComposite: null,
// 吸管取样用的合成画布缓存(切工具/画布变化时失效)
// v1.8 快速效果的「可重调」状态:source 是点效果那一刻的像素备份,
// 拖强度滑杆时一律从 source 重算,绝不在上一次结果上叠加(否则来回拖会越拖越糊)。
// layerId 用于判断源是否还对得上当前目标层:切层后滑杆自动置灰,切回即恢复。
fx: { key: null, value: 0, layerId: null, source: null },
rectFill: false,
// 矩形/圆形是否实心填充
penFill: true,
@@ -172,6 +176,20 @@ var __IWB_ANNOTATE_MANIFEST__ = {
};
var runtime = { el: null };
// image-annotate/plugin/editor/scale.js
function viewScale() {
return S.imgW && S.fitW ? S.fitW * S.zoom / S.imgW : 1;
}
function overlayScale() {
const base = S.imgW && S.fitW ? S.fitW / S.imgW : 1;
return Math.max(1, Math.min(4, base));
}
function resetOverlayTransform(cx) {
const k = overlayScale();
const pad = S.overlayPad || 0;
cx.setTransform(k, 0, 0, k, pad * k, pad * k);
}
// image-annotate/plugin/editor/placement.js
function commitImageAsLayer(img, x, y, w, h, rotation) {
const id = "L" + Date.now() + Math.floor(Math.random() * 1e3);
@@ -258,18 +276,18 @@ var __IWB_ANNOTATE_MANIFEST__ = {
const corners = boxCorners(x, y, w, h, rot);
ctx.save();
ctx.strokeStyle = "#4488ff";
ctx.lineWidth = 2 / S.zoom;
ctx.setLineDash([8 / S.zoom, 4 / S.zoom]);
ctx.lineWidth = 2 / viewScale();
ctx.setLineDash([8 / viewScale(), 4 / viewScale()]);
ctx.beginPath();
ctx.moveTo(corners[0][0], corners[0][1]);
for (let i = 1; i < corners.length; i++) ctx.lineTo(corners[i][0], corners[i][1]);
ctx.closePath();
ctx.stroke();
ctx.setLineDash([]);
const hs = 5.5 / S.zoom;
const hs = 5.5 / viewScale();
ctx.fillStyle = "#fff";
ctx.strokeStyle = "#4488ff";
ctx.lineWidth = 1.5 / S.zoom;
ctx.lineWidth = 1.5 / viewScale();
const localPts = {
nw: [x, y],
ne: [x + w, y],
@@ -290,17 +308,17 @@ var __IWB_ANNOTATE_MANIFEST__ = {
ctx.restore();
drawRotationHandles(ctx, { x, y, w, h }, rot);
ctx.save();
ctx.font = "bold " + Math.round(14 / S.zoom) + "px sans-serif";
ctx.font = "bold " + Math.round(14 / viewScale()) + "px sans-serif";
ctx.textAlign = "center";
ctx.textBaseline = "top";
const hintText = "拖拽手柄调整大小 · 圆点=旋转 · Shift=等比/15°吸附 · Enter=确认 · Esc=取消";
const br = boxCorners(x, y, w, h, rot).reduce((acc, pt) => Math.max(acc, pt[1]), -Infinity);
const hintY = br + 10 / S.zoom;
const hintY = br + 10 / viewScale();
const tw = ctx.measureText(hintText).width;
ctx.fillStyle = "rgba(0,0,0,0.6)";
ctx.fillRect(cx - tw / 2 - 6 / S.zoom, hintY, tw + 12 / S.zoom, 22 / S.zoom);
ctx.fillRect(cx - tw / 2 - 6 / viewScale(), hintY, tw + 12 / viewScale(), 22 / viewScale());
ctx.fillStyle = "rgba(255,255,255,0.95)";
ctx.fillText(hintText, cx, hintY + 4 / S.zoom);
ctx.fillText(hintText, cx, hintY + 4 / viewScale());
ctx.restore();
}
function hitPlacementHandle(pos) {
@@ -309,7 +327,7 @@ var __IWB_ANNOTATE_MANIFEST__ = {
const rot = S.placingImage.rotation || 0;
const cx = x + w / 2, cy = y + h / 2;
const lp = unrotPt(pos.x, pos.y, cx, cy, rot);
const R = 12 / S.zoom;
const R = 12 / viewScale();
if (hitRotationHandle(lp, { x, y, w, h })) return "rotate";
const pts = {
nw: [x, y],
@@ -639,12 +657,11 @@ var __IWB_ANNOTATE_MANIFEST__ = {
function clearToolRing() {
const ctx = S.cursorCtx;
if (!ctx) return;
const pad = S.overlayPad || 0;
ctx.save();
ctx.setTransform(1, 0, 0, 1, 0, 0);
ctx.clearRect(0, 0, S.imgW + pad * 2, S.imgH + pad * 2);
ctx.clearRect(0, 0, ctx.canvas.width, ctx.canvas.height);
ctx.restore();
ctx.setTransform(1, 0, 0, 1, pad, pad);
resetOverlayTransform(ctx);
}
function drawToolRing(pos) {
clearToolRing();
@@ -926,7 +943,7 @@ var __IWB_ANNOTATE_MANIFEST__ = {
const lp = rot ? unrotPt(pos.x, pos.y, b.x + b.w / 2, b.y + b.h / 2, rot) : [pos.x, pos.y];
if (hitRotationHandle(lp, b)) return "rotate";
const local = { nw: [b.x, b.y], ne: [b.x + b.w, b.y], sw: [b.x, b.y + b.h], se: [b.x + b.w, b.y + b.h] };
const R = 12 / S.zoom;
const R = 12 / viewScale();
let best = null, bestDist = 1e9;
for (const name in local) {
const dx = lp[0] - local[name][0], dy = lp[1] - local[name][1];
@@ -964,8 +981,8 @@ var __IWB_ANNOTATE_MANIFEST__ = {
}
if (s.type === "pen") {
const pts = s.pts || [];
for (let i = 1; i < pts.length; i++) if (distToSeg(pos.x, pos.y, pts[i - 1].x, pts[i - 1].y, pts[i].x, pts[i].y) <= Math.max(8 / S.zoom, s.lw)) return true;
if (s.closed && pts.length > 2 && distToSeg(pos.x, pos.y, pts[pts.length - 1].x, pts[pts.length - 1].y, pts[0].x, pts[0].y) <= Math.max(8 / S.zoom, s.lw)) return true;
for (let i = 1; i < pts.length; i++) if (distToSeg(pos.x, pos.y, pts[i - 1].x, pts[i - 1].y, pts[i].x, pts[i].y) <= Math.max(8 / viewScale(), s.lw)) return true;
if (s.closed && pts.length > 2 && distToSeg(pos.x, pos.y, pts[pts.length - 1].x, pts[pts.length - 1].y, pts[0].x, pts[0].y) <= Math.max(8 / viewScale(), s.lw)) return true;
if (!includeInterior) return false;
const b = shapeBounds(s);
return pos.x >= b.x && pos.x <= b.x + b.w && pos.y >= b.y && pos.y <= b.y + b.h;
@@ -977,7 +994,7 @@ var __IWB_ANNOTATE_MANIFEST__ = {
const nx = (pos.x - cx) / rx, ny = (pos.y - cy) / ry;
const value = nx * nx + ny * ny;
if (includeInterior || s.fill) return value <= 1;
const edgeTolerance = Math.max(4 / S.zoom, s.lw / Math.min(rx, ry));
const edgeTolerance = Math.max(4 / viewScale(), s.lw / Math.min(rx, ry));
const outer = (1 + edgeTolerance) * (1 + edgeTolerance);
const inner = Math.max(0, 1 - edgeTolerance) * Math.max(0, 1 - edgeTolerance);
return value >= inner && value <= outer;
@@ -991,7 +1008,7 @@ var __IWB_ANNOTATE_MANIFEST__ = {
const inInner = pos.x >= b.x + pad && pos.x <= b.x + b.w - pad && pos.y >= b.y + pad && pos.y <= b.y + b.h - pad;
return !inInner;
}
return distToSeg(pos.x, pos.y, s.x1, s.y1, s.x2, s.y2) <= Math.max(8 / S.zoom, s.lw);
return distToSeg(pos.x, pos.y, s.x1, s.y1, s.x2, s.y2) <= Math.max(8 / viewScale(), s.lw);
}
function hitShapeLayer(pos, includeInterior) {
for (let i = S.shapeLayers.length - 1; i >= 0; i--) {
@@ -1151,8 +1168,8 @@ var __IWB_ANNOTATE_MANIFEST__ = {
const lp = rot ? unrotPt(pos.x, pos.y, cx, cy, rot) : [pos.x, pos.y];
if (hitRotationHandle(lp, b)) return "rotate";
const pts = shapeHandlePoints(s);
const offset = 8 / S.zoom;
const R = Math.max(14 / S.zoom, 9);
const offset = 8 / viewScale();
const R = 14 / viewScale();
let best = null, bestDist = 1e9;
for (const name in pts) {
const px = pts[name][0] + (name.includes("w") ? -offset : name.includes("e") ? offset : 0);
@@ -1203,7 +1220,7 @@ var __IWB_ANNOTATE_MANIFEST__ = {
return;
}
const b = shapeBounds(s);
const offset = 8 / S.zoom;
const offset = 8 / viewScale();
const adjusted = { x: pos.x - (handle.includes("w") ? -offset : handle.includes("e") ? offset : 0), y: pos.y - (handle.includes("n") ? -offset : handle.includes("s") ? offset : 0) };
let x1 = b.x, y1 = b.y, x2 = b.x + b.w, y2 = b.y + b.h;
if (handle.includes("e")) x2 = Math.max(x1 + 2, adjusted.x);
@@ -1221,13 +1238,13 @@ var __IWB_ANNOTATE_MANIFEST__ = {
const ctx = S.overlayCtx;
const pts = path.pts.slice();
const first = pts[0];
const nearStart = path.preview && pts.length >= 3 && Math.hypot(path.preview.x - first.x, path.preview.y - first.y) <= Math.max(12 / S.zoom, S.shapeLineWidth * 1.5);
const nearStart = path.preview && pts.length >= 3 && Math.hypot(path.preview.x - first.x, path.preview.y - first.y) <= Math.max(12 / viewScale(), S.shapeLineWidth * 1.5);
if (path.preview) pts.push(nearStart ? first : path.preview);
ctx.save();
ctx.strokeStyle = S.color;
ctx.fillStyle = nearStart ? "rgba(232, 167, 53, 0.18)" : "transparent";
ctx.lineWidth = Math.max(1, S.shapeLineWidth) / S.zoom;
ctx.setLineDash([8 / S.zoom, 5 / S.zoom]);
ctx.lineWidth = Math.max(1, S.shapeLineWidth);
ctx.setLineDash([8 / viewScale(), 5 / viewScale()]);
ctx.beginPath();
ctx.moveTo(pts[0].x, pts[0].y);
for (let i = 1; i < pts.length; i++) ctx.lineTo(pts[i].x, pts[i].y);
@@ -1242,7 +1259,7 @@ var __IWB_ANNOTATE_MANIFEST__ = {
ctx.beginPath();
ctx.fillStyle = i === 0 && nearStart ? "#e8a735" : "#ffffff";
ctx.strokeStyle = S.color;
ctx.arc(point.x, point.y, Math.max(4, 6 / S.zoom), 0, Math.PI * 2);
ctx.arc(point.x, point.y, 6 / viewScale(), 0, Math.PI * 2);
ctx.fill();
ctx.stroke();
}
@@ -1254,8 +1271,8 @@ var __IWB_ANNOTATE_MANIFEST__ = {
const rot = s.rotation || 0;
octx.save();
octx.strokeStyle = "#e8a735";
octx.lineWidth = 1.5 / S.zoom;
octx.setLineDash([6 / S.zoom, 3 / S.zoom]);
octx.lineWidth = 1.5 / viewScale();
octx.setLineDash([6 / viewScale(), 3 / viewScale()]);
const corners = boxCorners(b.x, b.y, b.w, b.h, rot);
octx.beginPath();
octx.moveTo(corners[0][0], corners[0][1]);
@@ -1263,7 +1280,7 @@ var __IWB_ANNOTATE_MANIFEST__ = {
octx.closePath();
octx.stroke();
octx.setLineDash([]);
const hs = 5.5 / S.zoom;
const hs = 5.5 / viewScale();
octx.fillStyle = "#ffffff";
octx.strokeStyle = "#e8a735";
const pts = shapeHandleWorld(s);
@@ -1305,16 +1322,16 @@ var __IWB_ANNOTATE_MANIFEST__ = {
const octx = S.overlayCtx;
octx.save();
octx.strokeStyle = "#e8a735";
octx.lineWidth = 1.5 / S.zoom;
octx.setLineDash([6 / S.zoom, 3 / S.zoom]);
const corners = boxCorners(b.x - 2 / S.zoom, b.y - 2 / S.zoom, b.w + 4 / S.zoom, b.h + 4 / S.zoom, rot);
octx.lineWidth = 1.5 / viewScale();
octx.setLineDash([6 / viewScale(), 3 / viewScale()]);
const corners = boxCorners(b.x - 2 / viewScale(), b.y - 2 / viewScale(), b.w + 4 / viewScale(), b.h + 4 / viewScale(), rot);
octx.beginPath();
octx.moveTo(corners[0][0], corners[0][1]);
for (let i = 1; i < corners.length; i++) octx.lineTo(corners[i][0], corners[i][1]);
octx.closePath();
octx.stroke();
octx.setLineDash([]);
const hs = 5.5 / S.zoom;
const hs = 5.5 / viewScale();
octx.fillStyle = "#ffffff";
octx.strokeStyle = "#e8a735";
const pts = textHandlePoints(sel);
@@ -1371,7 +1388,7 @@ var __IWB_ANNOTATE_MANIFEST__ = {
const pts = shape.pts || [];
const b = shapeBounds(shape);
const lp = shape.rotation ? unrotPt(pos.x, pos.y, b.x + b.w / 2, b.y + b.h / 2, shape.rotation) : [pos.x, pos.y];
const r = Math.max(12 / S.zoom, 6);
const r = 12 / viewScale();
for (let i = 0; i < pts.length - 1; i++) {
if (distToSeg(lp[0], lp[1], pts[i].x, pts[i].y, pts[i + 1].x, pts[i + 1].y) <= r) return i;
}
@@ -1387,9 +1404,9 @@ var __IWB_ANNOTATE_MANIFEST__ = {
const rot = shape.rotation || 0;
const cx = b.x + b.w / 2, cy = b.y + b.h / 2;
const W = (p) => rotPt(p.x, p.y, cx, cy, rot);
const R = Math.max(7 / S.zoom, 5);
const R = 7 / viewScale();
ctx.save();
ctx.lineWidth = 1.5 / S.zoom;
ctx.lineWidth = 1.5 / viewScale();
const segments = [];
for (let i = 0; i < pts.length - 1; i++) segments.push([pts[i], pts[i + 1]]);
if (shape.closed && pts.length >= 3) segments.push([pts[pts.length - 1], pts[0]]);
@@ -1398,7 +1415,7 @@ var __IWB_ANNOTATE_MANIFEST__ = {
const wa = W(a), wb = W(bb);
const mx = (wa[0] + wb[0]) / 2, my = (wa[1] + wb[1]) / 2;
ctx.beginPath();
ctx.arc(mx, my, Math.max(3 / S.zoom, 2), 0, Math.PI * 2);
ctx.arc(mx, my, 3 / viewScale(), 0, Math.PI * 2);
ctx.stroke();
}
for (let i = 0; i < pts.length; i++) {
@@ -1638,7 +1655,7 @@ var __IWB_ANNOTATE_MANIFEST__ = {
const rot = layer.rotation || 0;
const cx = box.x + box.w / 2, cy = box.y + box.h / 2;
const lp = unrotPt(pos.x, pos.y, cx, cy, rot);
const R = 14 / S.zoom;
const R = 14 / viewScale();
if (hitRotationHandle(lp, box)) return "rotate";
const points = {
nw: [box.x, box.y],
@@ -1718,11 +1735,11 @@ var __IWB_ANNOTATE_MANIFEST__ = {
if (!(box.w > 0 && box.h > 0)) return;
const ctx = S.overlayCtx;
const rot = layer.rotation || 0;
const hs = 5.5 / S.zoom;
const hs = 5.5 / viewScale();
ctx.save();
ctx.strokeStyle = "#e8a735";
ctx.lineWidth = 1.5 / S.zoom;
ctx.setLineDash([6 / S.zoom, 3 / S.zoom]);
ctx.lineWidth = 1.5 / viewScale();
ctx.setLineDash([6 / viewScale(), 3 / viewScale()]);
const corners = boxCorners(box.x, box.y, box.w, box.h, rot);
ctx.beginPath();
ctx.moveTo(corners[0][0], corners[0][1]);
@@ -1846,6 +1863,7 @@ var __IWB_ANNOTATE_MANIFEST__ = {
if (!changed) return;
renderLayerPanel();
renderObjects();
if (S.renderFxPanel) S.renderFxPanel();
}
function addBitmapLayer(img) {
placeImageDirectly(img);
@@ -2548,28 +2566,26 @@ var __IWB_ANNOTATE_MANIFEST__ = {
function clearSelectionCanvas() {
const ctx = S.selectionCtx;
if (!ctx) return;
const pad = S.overlayPad || 0;
ctx.save();
ctx.setTransform(1, 0, 0, 1, 0, 0);
ctx.clearRect(0, 0, S.imgW + pad * 2, S.imgH + pad * 2);
ctx.clearRect(0, 0, ctx.canvas.width, ctx.canvas.height);
ctx.restore();
ctx.setTransform(1, 0, 0, 1, pad, pad);
resetOverlayTransform(ctx);
}
function clearCursorCanvas() {
const ctx = S.cursorCtx;
if (!ctx) return;
const pad = S.overlayPad || 0;
ctx.save();
ctx.setTransform(1, 0, 0, 1, 0, 0);
ctx.clearRect(0, 0, S.imgW + pad * 2, S.imgH + pad * 2);
ctx.clearRect(0, 0, ctx.canvas.width, ctx.canvas.height);
ctx.restore();
ctx.setTransform(1, 0, 0, 1, pad, pad);
resetOverlayTransform(ctx);
}
function renderSelection() {
if (!S.selectionCtx) return;
clearSelectionCanvas();
const ctx = S.selectionCtx;
const k = 1 / Math.max(S.zoom, 1e-4);
const k = 1 / Math.max(viewScale(), 1e-4);
if (S.marquee || S.lassoPts && S.lassoPts.length > 1) {
ctx.save();
ctx.lineWidth = 1.5 * k;
@@ -3190,7 +3206,15 @@ var __IWB_ANNOTATE_MANIFEST__ = {
<span class="iwb-editor-fx-ico ico-mosaic"></span><span>马赛克</span>
</button>
</div>
<p class="iwb-editor-fx-tip">作用于当前层 · Ctrl+Z 可撤销</p>
<!-- v1.8:效果参数。点效果后启用,范围/单位随效果切换(马赛克=块大小,柔化=半径,其余=强度) -->
<div class="iwb-editor-fx-adj iwb-editor-fx-adj-off">
<div class="iwb-editor-fx-adj-head">
<span class="iwb-editor-fx-adj-name">强度</span>
<span class="iwb-editor-fx-adj-val">—</span>
</div>
<input type="range" class="iwb-editor-fx-range" min="0" max="100" step="1" value="0" disabled aria-label="效果强度">
</div>
<p class="iwb-editor-fx-tip">先点效果,再拖强度微调 · Ctrl+Z 撤销</p>
</section>
<div class="iwb-editor-zoom">
@@ -3303,24 +3327,100 @@ var __IWB_ANNOTATE_MANIFEST__ = {
}
// image-annotate/plugin/editor/effects.js
var QUICK_EFFECTS = {
invert: { label: "反白", hint: "反相:明暗翻转,白底变黑底", css: () => "invert(1)" },
gray: { label: "灰度", hint: "去色,保留明暗层次", css: () => "grayscale(1)" },
boost: { label: "增强", hint: "提亮并略加对比", css: () => "brightness(1.12) contrast(1.1) saturate(1.06)" },
contrast: { label: "高对比", hint: "压成黑白硬调", css: () => "grayscale(1) contrast(2.4)" },
soft: { label: "柔化", hint: "轻微模糊,弱化背景", css: (c) => "blur(" + softRadius(c) + "px)" },
mosaic: { label: "马赛克", hint: "像素化,用于打码", pixel: true }
};
var SOFT_MIN = 0.8;
var SOFT_MIN = 1.2;
var SOFT_MAX = 8;
function softRadius(canvas) {
const side = Math.min(canvas.width || 0, canvas.height || 0);
return Math.max(SOFT_MIN, Math.min(SOFT_MAX, Math.round(side / 500 * 10) / 10));
return Math.max(SOFT_MIN, Math.min(SOFT_MAX, Math.round(side / 400 * 10) / 10));
}
function mosaicBlock(canvas) {
const side = Math.min(canvas.width || 0, canvas.height || 0);
return Math.max(6, Math.round(side / 60));
}
var QUICK_EFFECTS = {
invert: {
label: "反白",
hint: "反相:明暗翻转,白底变黑底",
param: "强度",
unit: "%",
min: 0,
max: 100,
step: 1,
def: () => 100,
render: (canvas, v) => {
if (v > 0) filterCanvas(canvas, "invert(" + v / 100 + ")");
}
},
gray: {
label: "灰度",
hint: "去色,保留明暗层次",
param: "强度",
unit: "%",
min: 0,
max: 100,
step: 1,
def: () => 100,
render: (canvas, v) => {
if (v > 0) filterCanvas(canvas, "grayscale(" + v / 100 + ")");
}
},
boost: {
label: "增强",
hint: "提亮并略加对比,适合发灰的截图",
param: "强度",
unit: "%",
min: 0,
max: 100,
step: 1,
def: () => 100,
render: (canvas, v) => {
if (v <= 0) return;
const k = v / 100;
filterCanvas(canvas, "brightness(" + (1 + 0.12 * k).toFixed(3) + ") contrast(" + (1 + 0.1 * k).toFixed(3) + ") saturate(" + (1 + 0.06 * k).toFixed(3) + ")");
}
},
contrast: {
label: "高对比",
hint: "压成黑白硬调,突出主体",
param: "强度",
unit: "%",
min: 0,
max: 100,
step: 1,
def: () => 100,
render: (canvas, v) => {
if (v <= 0) return;
const k = v / 100;
filterCanvas(canvas, "grayscale(" + k.toFixed(3) + ") contrast(" + (1 + 1.4 * k).toFixed(3) + ")");
}
},
soft: {
label: "柔化",
hint: "模糊,弱化背景",
param: "半径",
unit: "px",
min: 0,
max: 16,
step: 0.5,
def: (canvas) => softRadius(canvas),
render: (canvas, v) => {
if (v > 0) filterCanvas(canvas, "blur(" + v + "px)");
}
},
mosaic: {
label: "马赛克",
hint: "像素化,用于打码手机号/地址等隐私信息",
param: "块大小",
unit: "px",
min: 2,
max: 96,
step: 1,
def: (canvas) => mosaicBlock(canvas),
render: (canvas, v) => {
if (v > 1) pixelateCanvas(canvas, v);
}
}
};
function effectTarget() {
const active = getActiveLayer();
if (active) return active;
@@ -3347,8 +3447,9 @@ var __IWB_ANNOTATE_MANIFEST__ = {
function pixelateCanvas(canvas, block) {
const w = canvas.width, h = canvas.height;
if (!w || !h) return;
const sw = Math.max(1, Math.round(w / block));
const sh = Math.max(1, Math.round(h / block));
const b = Math.max(2, block);
const sw = Math.max(1, Math.round(w / b));
const sh = Math.max(1, Math.round(h / b));
const tmp = document.createElement("canvas");
tmp.width = sw;
tmp.height = sh;
@@ -3365,6 +3466,14 @@ var __IWB_ANNOTATE_MANIFEST__ = {
ctx.drawImage(tmp, 0, 0, w, h);
ctx.restore();
}
function snapshotCanvas(canvas) {
const c = document.createElement("canvas");
c.width = canvas.width;
c.height = canvas.height;
const ctx = c.getContext("2d");
ctx.drawImage(canvas, 0, 0);
return c;
}
function rasterizeLayer(layer) {
const canvas = createLayerCanvas();
const ctx = canvas.getContext("2d", { willReadFrequently: true });
@@ -3399,6 +3508,70 @@ var __IWB_ANNOTATE_MANIFEST__ = {
renderLayerPanel();
return clone;
}
function renderFromSource(target, key, value) {
const st = S.fx;
const fx = QUICK_EFFECTS[key];
if (!st.source || !fx) return;
const ctx = target.canvas.getContext("2d");
ctx.save();
ctx.setTransform(1, 0, 0, 1, 0, 0);
ctx.globalAlpha = 1;
ctx.globalCompositeOperation = "copy";
ctx.filter = "none";
ctx.imageSmoothingEnabled = true;
ctx.drawImage(st.source, 0, 0);
ctx.restore();
fx.render(target.canvas, value);
target._bounds = void 0;
S.pickerComposite = null;
}
function fmtValue(fx, v) {
if (fx.unit === "px") return Math.round(v * 10) / 10 + " px";
return Math.round(v) + "%";
}
function renderFxPanel() {
if (!runtime.el) return;
const adv = runtime.el.querySelector(".iwb-editor-fx-adj");
if (!adv) return;
const range = adv.querySelector(".iwb-editor-fx-range");
const nameEl = adv.querySelector(".iwb-editor-fx-adj-name");
const valEl = adv.querySelector(".iwb-editor-fx-adj-val");
const targetEl = runtime.el.querySelector(".iwb-editor-fx-target");
const layer = effectTarget();
const activeKey = S.fx.source ? S.fx.key : null;
runtime.el.querySelectorAll("[data-fx]").forEach((btn) => {
btn.classList.toggle("is-active", Boolean(activeKey) && btn.dataset.fx === activeKey);
});
if (targetEl) {
const name = layer ? layer.name : "无图层";
targetEl.textContent = name;
targetEl.title = layer ? "效果作用于「" + name + "」" : "没有可处理的位图图层";
}
const st = S.fx;
const fx = st.source ? QUICK_EFFECTS[st.key] : null;
if (!fx || !range) {
adv.classList.add("iwb-editor-fx-adj-off");
if (nameEl) nameEl.textContent = "强度";
if (valEl) valEl.textContent = "—";
if (range) {
range.disabled = true;
range.value = "0";
}
return;
}
const usable = Boolean(layer && st.layerId === layer.id);
adv.classList.toggle("iwb-editor-fx-adj-off", !usable);
if (nameEl) nameEl.textContent = fx.label + " · " + fx.param;
range.min = String(fx.min);
range.max = String(fx.max);
range.step = String(fx.step);
range.disabled = !usable;
if (usable) range.value = String(st.value);
if (valEl) {
valEl.textContent = fmtValue(fx, st.value);
valEl.title = usable ? "" : "效果作用在「" + (S.layers.find((l) => l.id === st.layerId) || {}).name + "」,切回该层可继续调整";
}
}
function applyQuickEffect(key) {
const fx = QUICK_EFFECTS[key];
if (!fx) return false;
@@ -3411,20 +3584,43 @@ var __IWB_ANNOTATE_MANIFEST__ = {
toast("「" + layer.name + "」已隐藏,先显示再应用效果");
return false;
}
saveSnapshot("效果:" + fx.label);
let target = layer;
if (!needsPixelSnapshot(layer)) target = rasterizeLayer(layer);
if (!target) {
toast("栅格化失败,效果未应用");
return false;
}
if (fx.pixel) pixelateCanvas(target.canvas, mosaicBlock(target.canvas));
else filterCanvas(target.canvas, fx.css(target.canvas));
target._bounds = void 0;
S.pickerComposite = null;
const st = S.fx;
if (st.source && st.layerId === target.id && st.key === key) {
st.value = fx.def(target.canvas);
renderFromSource(target, key, st.value);
if (S.renderAll) S.renderAll();
toast("「" + fx.label + "」已重置为 " + fmtValue(fx, st.value), "success");
return true;
}
saveSnapshot("效果:" + fx.label);
S.fx = { key, layerId: target.id, source: snapshotCanvas(target.canvas), value: fx.def(target.canvas) };
renderFromSource(target, key, S.fx.value);
if (S.renderAll) S.renderAll();
renderLayerPanel();
toast("已应用「" + fx.label + "」到 " + target.name + " · Ctrl+Z 撤销", "success");
toast("已应用「" + fx.label + "」" + fmtValue(fx, S.fx.value) + " 到 " + target.name + " · 可拖强度微调", "success");
return true;
}
function setEffectValue(value) {
const st = S.fx;
if (!st.source) return false;
const fx = QUICK_EFFECTS[st.key];
if (!fx) return false;
const target = S.layers.find((l) => l.id === st.layerId);
if (!target) return false;
const layer = effectTarget();
if (!layer || layer.id !== st.layerId) return false;
const v = Math.min(fx.max, Math.max(fx.min, Number(value) || 0));
st.value = v;
renderFromSource(target, st.key, v);
if (runtime.el) {
const valEl = runtime.el.querySelector(".iwb-editor-fx-adj-val");
if (valEl) valEl.textContent = fmtValue(fx, v);
}
return true;
}
@@ -3485,14 +3681,14 @@ var __IWB_ANNOTATE_MANIFEST__ = {
function isDoubleClick(pos) {
const now = typeof performance !== "undefined" && performance.now ? performance.now() : Date.now();
const last = S.lastClick;
const hit = !!last && now - last.t < DBL_INTERVAL && Math.hypot(pos.x - last.x, pos.y - last.y) < Math.max(8 / S.zoom, 6);
const hit = !!last && now - last.t < DBL_INTERVAL && Math.hypot(pos.x - last.x, pos.y - last.y) < Math.max(8 / viewScale(), 6);
S.lastClick = hit ? null : { t: now, x: pos.x, y: pos.y };
return hit;
}
function onCanvasDoubleClick(e, pos) {
const penShape = getPenEditingShape();
if (penShape) {
const pi = hitPenPoint(pos, penShape, Math.max(14 / S.zoom, 8));
const pi = hitPenPoint(pos, penShape, Math.max(14 / viewScale(), 8));
if (pi < 0) return false;
e.preventDefault();
saveSnapshot();
@@ -3554,7 +3750,7 @@ var __IWB_ANNOTATE_MANIFEST__ = {
updateCursor();
}
function onPenEditMouseDown(e, pos, penShape) {
const pi = hitPenPoint(pos, penShape, Math.max(16 / S.zoom, 9));
const pi = hitPenPoint(pos, penShape, Math.max(16 / viewScale(), 9));
if (pi >= 0) {
S.penDragPt = pi;
S.penDragBase = JSON.parse(JSON.stringify(penShape.pts));
@@ -3686,7 +3882,7 @@ var __IWB_ANNOTATE_MANIFEST__ = {
if (!S.penPath) S.penPath = { pts: [], preview: null, closed: false };
const point = { x: clamp(pos.x, 0, S.imgW), y: clamp(pos.y, 0, S.imgH) };
const first = S.penPath.pts[0];
if (first && S.penPath.pts.length >= 3 && Math.hypot(point.x - first.x, point.y - first.y) <= Math.max(12 / S.zoom, S.shapeLineWidth * 1.5)) {
if (first && S.penPath.pts.length >= 3 && Math.hypot(point.x - first.x, point.y - first.y) <= Math.max(12 / viewScale(), S.shapeLineWidth * 1.5)) {
S.penPath.closed = true;
S.penPath.nearStart = true;
S.penPath.preview = null;
@@ -3858,7 +4054,7 @@ var __IWB_ANNOTATE_MANIFEST__ = {
if (S.penPath) {
S.penPath.preview = pos;
const first = S.penPath.pts[0];
const nearStart = first && S.penPath.pts.length >= 3 && Math.hypot(pos.x - first.x, pos.y - first.y) <= Math.max(12 / S.zoom, S.shapeLineWidth * 1.5);
const nearStart = first && S.penPath.pts.length >= 3 && Math.hypot(pos.x - first.x, pos.y - first.y) <= Math.max(12 / viewScale(), S.shapeLineWidth * 1.5);
S.penPath.nearStart = !!nearStart;
renderObjects();
}
@@ -4527,6 +4723,19 @@ var __IWB_ANNOTATE_MANIFEST__ = {
closeMenus();
});
});
const fxRangeOf = (e) => e.target && e.target.closest ? e.target.closest(".iwb-editor-fx-range") : null;
root.addEventListener("input", (e) => {
const range = fxRangeOf(e);
if (!range) return;
e.stopPropagation();
setEffectValue(parseFloat(range.value));
});
root.addEventListener("change", (e) => {
const range = fxRangeOf(e);
if (!range) return;
e.stopPropagation();
if (S.renderAll) S.renderAll();
});
const body = root.querySelector(".iwb-editor-optionbar-body");
if (body) {
body.addEventListener("mousedown", (e) => e.stopPropagation());
@@ -5454,11 +5663,13 @@ var __IWB_ANNOTATE_MANIFEST__ = {
S.strokeCanvas.height = S.imgH;
S.strokeCanvas.style.display = "none";
S.overlayPad = Math.max(96, Math.ceil(Math.max(S.imgW, S.imgH) * 0.18));
computeFit();
const uiK = overlayScale();
for (const [c, cx] of [[S.overlayCanvas, S.overlayCtx], [S.selectionCanvas, S.selectionCtx], [S.cursorCanvas, S.cursorCtx]]) {
if (!c || !cx) continue;
c.width = S.imgW + S.overlayPad * 2;
c.height = S.imgH + S.overlayPad * 2;
cx.setTransform(1, 0, 0, 1, S.overlayPad, S.overlayPad);
c.width = Math.round((S.imgW + S.overlayPad * 2) * uiK);
c.height = Math.round((S.imgH + S.overlayPad * 2) * uiK);
resetOverlayTransform(cx);
}
const baseCanvas = createLayerCanvas();
const baseCtx = baseCanvas.getContext("2d", { willReadFrequently: true });
@@ -5481,7 +5692,6 @@ var __IWB_ANNOTATE_MANIFEST__ = {
clearOverlay();
S.pickerComposite = null;
renderObjects();
computeFit();
S.viewX = null;
applyView();
renderLayerPanel();
@@ -5495,11 +5705,13 @@ var __IWB_ANNOTATE_MANIFEST__ = {
S.strokeCanvas.width = S.imgW;
S.strokeCanvas.height = S.imgH;
S.overlayPad = Math.max(96, Math.ceil(Math.max(S.imgW, S.imgH) * 0.18));
computeFit();
const uiK = overlayScale();
for (const [c, cx] of [[S.overlayCanvas, S.overlayCtx], [S.selectionCanvas, S.selectionCtx], [S.cursorCanvas, S.cursorCtx]]) {
if (!c || !cx) continue;
c.width = S.imgW + S.overlayPad * 2;
c.height = S.imgH + S.overlayPad * 2;
cx.setTransform(1, 0, 0, 1, S.overlayPad, S.overlayPad);
c.width = Math.round((S.imgW + S.overlayPad * 2) * uiK);
c.height = Math.round((S.imgH + S.overlayPad * 2) * uiK);
resetOverlayTransform(cx);
}
purgeVectorCanvases();
for (const layer of S.layers) {
@@ -5509,7 +5721,6 @@ var __IWB_ANNOTATE_MANIFEST__ = {
}
S.pickerComposite = null;
clearOverlay();
computeFit();
S.viewX = null;
applyView();
renderObjects();
@@ -5609,7 +5820,7 @@ var __IWB_ANNOTATE_MANIFEST__ = {
}
function rotationHandlesLocal(b) {
const cx = b.x + b.w / 2, cy = b.y + b.h / 2;
const d = 26 / Math.max(S.zoom, 1e-4);
const d = 26 / Math.max(viewScale(), 1e-4);
return [[b.x, b.y], [b.x + b.w, b.y], [b.x + b.w, b.y + b.h], [b.x, b.y + b.h]].map((c) => {
const dx = c[0] - cx, dy = c[1] - cy, len = Math.hypot(dx, dy) || 1;
return [c[0] + dx / len * d, c[1] + dy / len * d];
@@ -5617,7 +5828,7 @@ var __IWB_ANNOTATE_MANIFEST__ = {
}
function hitRotationHandle(lp, b) {
const pts = rotationHandlesLocal(b);
const R = Math.max(11 / Math.max(S.zoom, 1e-4), 8);
const R = 11 / Math.max(viewScale(), 1e-4);
for (const pt of pts) {
if (Math.hypot(lp[0] - pt[0], lp[1] - pt[1]) < R) return true;
}
@@ -5626,10 +5837,10 @@ var __IWB_ANNOTATE_MANIFEST__ = {
function drawRotationHandles(ctx, b, rot) {
const cx = b.x + b.w / 2, cy = b.y + b.h / 2;
const pts = rotationHandlesLocal(b);
const k = Math.max(S.zoom, 1e-4);
const r = Math.max(6.5 / k, 5);
const k = Math.max(viewScale(), 1e-4);
const r = 6.5 / k;
const lw = 1.5 / k;
const ah = Math.max(3 / k, 2.6);
const ah = 3 / k;
const A0 = Math.PI * 0.2, A1 = Math.PI * 1.72;
ctx.save();
ctx.strokeStyle = "#f0b34e";
@@ -5755,12 +5966,12 @@ var __IWB_ANNOTATE_MANIFEST__ = {
}
function clearOverlay() {
const ctx = S.overlayCtx;
const pad = S.overlayPad || 0;
if (!ctx) return;
ctx.save();
ctx.setTransform(1, 0, 0, 1, 0, 0);
ctx.clearRect(0, 0, S.imgW + pad * 2, S.imgH + pad * 2);
ctx.clearRect(0, 0, ctx.canvas.width, ctx.canvas.height);
ctx.restore();
ctx.setTransform(1, 0, 0, 1, pad, pad);
resetOverlayTransform(ctx);
}
function drawCropPreview(x1, y1, x2, y2) {
const ctx = S.overlayCtx;
@@ -5789,8 +6000,8 @@ var __IWB_ANNOTATE_MANIFEST__ = {
ctx.restore();
ctx.save();
ctx.strokeStyle = "#4488ff";
ctx.lineWidth = 2 / S.zoom;
ctx.setLineDash([8 / S.zoom, 4 / S.zoom]);
ctx.lineWidth = 2 / viewScale();
ctx.setLineDash([8 / viewScale(), 4 / viewScale()]);
ctx.strokeRect(rx, ry, rw, rh);
ctx.restore();
if (S.cropRect && !S.cropHandle) drawCropHandles(rx, ry, rw, rh);
@@ -5810,11 +6021,11 @@ var __IWB_ANNOTATE_MANIFEST__ = {
function drawCropHandles(rx, ry, rw, rh) {
const ctx = S.overlayCtx;
const pts = cropHandlePoints(rx, ry, rw, rh);
const hs = 4 / S.zoom;
const hs = 4 / viewScale();
ctx.save();
ctx.fillStyle = "#ffffff";
ctx.strokeStyle = "#4488ff";
ctx.lineWidth = 1.5 / S.zoom;
ctx.lineWidth = 1.5 / viewScale();
for (const name in pts) {
ctx.beginPath();
ctx.rect(pts[name][0] - hs, pts[name][1] - hs, hs * 2, hs * 2);
@@ -5829,7 +6040,7 @@ var __IWB_ANNOTATE_MANIFEST__ = {
function hitCropHandle(pos) {
if (!S.cropRect) return null;
const pts = cropHandlePoints(S.cropRect.x, S.cropRect.y, S.cropRect.w, S.cropRect.h);
const R = 12 / S.zoom;
const R = 12 / viewScale();
let best = null, bestDist = 1e9;
for (const name in pts) {
const dx = pos.x - pts[name][0], dy = pos.y - pts[name][1];
@@ -6628,6 +6839,7 @@ var __IWB_ANNOTATE_MANIFEST__ = {
S.callbacks = options;
S.renderAll = renderAll;
S.positionFloating = positionFloating;
S.renderFxPanel = renderFxPanel;
try {
const img = await loadImage(options.imageBase64);
S.imgW = img.naturalWidth || img.width;
@@ -6694,6 +6906,7 @@ var __IWB_ANNOTATE_MANIFEST__ = {
S.lastClick = null;
S.lastNameClick = null;
S.altPicker = false;
S.fx = { key: null, value: 0, layerId: null, source: null };
S.zCounter = Math.max(S.layers.length - 1, 0);
S.placingImage = null;
S.placingHandle = null;
@@ -6716,16 +6929,16 @@ var __IWB_ANNOTATE_MANIFEST__ = {
hideSelectionContext();
if (S.selectionCtx) renderSelection();
if (S.cursorCtx) {
const pad = S.overlayPad || 0;
S.cursorCtx.setTransform(1, 0, 0, 1, 0, 0);
S.cursorCtx.clearRect(0, 0, S.imgW + pad * 2, S.imgH + pad * 2);
S.cursorCtx.setTransform(1, 0, 0, 1, pad, pad);
S.cursorCtx.clearRect(0, 0, S.cursorCtx.canvas.width, S.cursorCtx.canvas.height);
resetOverlayTransform(S.cursorCtx);
}
}
function renderAll() {
if (!S.open || !runtime.el) return;
renderObjects();
renderLayerPanel();
renderFxPanel();
renderOptionBar();
updateStatusbar();
renderExportUI();
@@ -6774,6 +6987,7 @@ var __IWB_ANNOTATE_MANIFEST__ = {
S.redoStack = [];
S.originalImage = null;
S.pickerComposite = null;
S.fx = { key: null, value: 0, layerId: null, source: null };
S.isDrawing = false;
S.panning = false;
S.penDragPt = -1;
@@ -6875,9 +7089,47 @@ var __IWB_ANNOTATE_MANIFEST__ = {
redo: S.redoStack.length,
exportOptions: S.exportOptions ? { ...S.exportOptions } : null,
lastExport: S.lastExport ? { ...S.lastExport } : null,
// 快速效果的可重调状态:hasSource=false 表示还没点过效果(滑杆应置灰)
fx: { key: S.fx.key, value: S.fx.value, layerId: S.fx.layerId, hasSource: Boolean(S.fx.source) },
interaction: S.interaction,
ants: !!S._antFrame,
view: S.viewX !== null ? [Math.round(S.viewX), Math.round(S.viewY)] : null,
// 图层整幅像素指纹(抽样校验和):断言「改强度后从基准重算」而不是叠加,
// 比逐点采样稳 —— 马赛克/模糊的差异散在整幅,单点可能刚好相同
layerHash: (id) => {
const l = S.layers.find((v) => v.id === id);
if (!l || !l.ctx || !l.canvas) return 0;
try {
const d = l.ctx.getImageData(0, 0, l.canvas.width, l.canvas.height).data;
let h = 2166136261;
for (let i = 0; i < d.length; i += 97) {
h ^= d[i];
h = Math.imul(h, 16777619);
}
return h >>> 0;
} catch (e) {
return 0;
}
},
// 非透明像素的平均色:断言效果是否落在预期值上(如反相 50% 必然趋近 128)
avgColor: (id) => {
const l = S.layers.find((v) => v.id === id);
if (!l || !l.ctx || !l.canvas) return null;
try {
const d = l.ctx.getImageData(0, 0, l.canvas.width, l.canvas.height).data;
let r = 0, g = 0, b = 0, n = 0;
for (let i = 0; i < d.length; i += 4) {
if (d[i + 3] < 200) continue;
r += d[i];
g += d[i + 1];
b += d[i + 2];
n++;
}
return n ? [Math.round(r / n), Math.round(g / n), Math.round(b / n), n] : null;
} catch (e) {
return null;
}
},
pixel: (id, x, y) => {
const l = S.layers.find((v) => v.id === id);
if (!l || !l.ctx) return null;
@@ -6911,7 +7163,7 @@ var __IWB_ANNOTATE_MANIFEST__ = {
};
// image-annotate/plugin/editor.css
var editor_default = '/* IWB 鲜艺抠图节点 - 注入样式 */\n\n/* 抠图按钮 */\n.iwb-cutout-btn {\n cursor: pointer;\n opacity: 0.7;\n transition: opacity 0.15s, transform 0.15s;\n}\n\n.iwb-cutout-btn:hover {\n opacity: 1;\n transform: scale(1.15);\n}\n\n.iwb-cutout-btn svg {\n width: 14px;\n height: 14px;\n display: block;\n}\n\n/* 正在处理中的按钮状态 */\n.iwb-cutout-btn.processing {\n animation: iwb-cutout-pulse 1s infinite;\n pointer-events: none;\n}\n\n@keyframes iwb-cutout-pulse {\n 0%, 100% { opacity: 0.4; }\n 50% { opacity: 1; }\n}\n\n/* 全屏遮罩 */\n.iwb-cutout-overlay {\n position: fixed;\n top: 0;\n left: 0;\n width: 100%;\n height: 100%;\n background: rgba(0, 0, 0, 0.25);\n display: none;\n align-items: center;\n justify-content: center;\n flex-direction: column;\n gap: 12px;\n z-index: 999999;\n pointer-events: all;\n backdrop-filter: blur(2px);\n}\n\n/* 自定义按钮提示(挂在 body,最高层级,不会被图片遮挡) */\n#iwb-cutout-tip {\n position: fixed;\n z-index: 2147483647;\n background: rgba(30, 30, 46, 0.95);\n color: #fff;\n padding: 5px 10px;\n border-radius: 6px;\n font-size: 12px;\n line-height: 1.5;\n white-space: nowrap;\n pointer-events: none;\n display: none;\n box-shadow: 0 2px 8px rgba(0, 0, 0, 0.35);\n border: 1px solid rgba(255, 255, 255, 0.14);\n font-family: system-ui, -apple-system, "Segoe UI", sans-serif;\n max-width: 320px;\n white-space: normal;\n word-break: break-all;\n}\n\n/* 加载动画 */\n.iwb-cutout-spinner {\n width: 48px;\n height: 48px;\n border: 4px solid rgba(255, 255, 255, 0.3);\n border-top-color: #e8a735;\n border-radius: 50%;\n animation: iwb-cutout-spin 0.8s linear infinite;\n}\n\n@keyframes iwb-cutout-spin {\n to { transform: rotate(360deg); }\n}\n\n/* 遮罩文字 */\n.iwb-cutout-text {\n color: #fff;\n font-size: 14px;\n font-weight: 500;\n text-shadow: 0 1px 3px rgba(0, 0, 0, 0.5);\n background: rgba(0, 0, 0, 0.6);\n padding: 8px 16px;\n border-radius: 6px;\n}\n\n/* Toast 提示 */\n.iwb-cutout-toast {\n position: fixed;\n bottom: 24px;\n left: 50%;\n transform: translateX(-50%);\n padding: 10px 20px;\n border-radius: 8px;\n font-size: 13px;\n font-weight: 500;\n z-index: 999999;\n transition: opacity 0.3s;\n box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);\n display: none;\n max-width: 400px;\n}\n\n.iwb-cutout-toast-success {\n background: #1a7f37;\n color: #fff;\n}\n\n.iwb-cutout-toast-error {\n background: #cf222e;\n color: #fff;\n}\n\n.iwb-cutout-toast-info {\n background: #1f6feb;\n color: #fff;\n}\n\n/* 白底按钮 */\n.iwb-whitebg-btn {\n cursor: pointer;\n opacity: 0.7;\n transition: opacity 0.15s, transform 0.15s;\n}\n.iwb-whitebg-btn:hover { opacity: 1; transform: scale(1.15); }\n.iwb-whitebg-btn svg { width: 14px; height: 14px; display: block; }\n.iwb-whitebg-btn.processing { animation: iwb-cutout-pulse 1s infinite; pointer-events: none; }\n\n/* 编辑按钮 */\n.iwb-editor-btn-icon {\n cursor: pointer;\n opacity: 0.7;\n transition: opacity 0.15s, transform 0.15s;\n}\n.iwb-editor-btn-icon:hover { opacity: 1; transform: scale(1.15); }\n.iwb-editor-btn-icon svg { width: 14px; height: 14px; display: block; }\n\n/* ==================== 图片编辑器 ==================== */\n\n.iwb-editor-overlay {\n position: fixed;\n top: 0; left: 0;\n width: 100%; height: 100%;\n background: rgba(0, 0, 0, 0.6);\n display: none;\n align-items: center;\n justify-content: center;\n z-index: 999998;\n backdrop-filter: blur(3px);\n}\n\n.iwb-editor-modal {\n background: #1e1e2e;\n border-radius: 0;\n box-shadow: none;\n display: flex;\n flex-direction: column;\n width: 100vw;\n height: 100vh;\n max-width: none;\n max-height: none;\n overflow: visible;\n}\n\n/* 新增:主区域(画布 + 图层面板)flex 布局 */\n.iwb-editor-main {\n display: flex;\n flex: 1 1 auto;\n min-height: 0;\n overflow: visible;\n}\n\n.iwb-editor-header {\n display: flex;\n align-items: center;\n gap: 12px;\n padding: 10px 16px;\n background: #181825;\n border-bottom: 1px solid #313244;\n flex-wrap: nowrap;\n}\n.iwb-editor-header > .iwb-editor-tools {\n position: absolute;\n left: 12px;\n top: 68px;\n width: 44px;\n flex-direction: column;\n padding: 6px;\n background: #181825;\n border: 1px solid #313244;\n border-radius: 8px;\n z-index: 20;\n}\n.iwb-editor-header > .iwb-editor-tools .iwb-editor-action { position: static; }\n.iwb-editor-header > .iwb-editor-tools .iwb-editor-action[data-action="undo"],\n.iwb-editor-header > .iwb-editor-tools .iwb-editor-action[data-action="redo"],\n.iwb-editor-header > .iwb-editor-tools .iwb-editor-action[data-action="reset"],\n.iwb-editor-header > .iwb-editor-tools .iwb-editor-action[data-action="restore"] {\n position: absolute;\n top: -54px;\n left: auto;\n}\n.iwb-editor-header > .iwb-editor-tools .iwb-editor-action[data-action="undo"] { right: 154px; }\n.iwb-editor-header > .iwb-edLine truncated
var editor_default = '/* IWB 鲜艺抠图节点 - 注入样式 */\n\n/* 抠图按钮 */\n.iwb-cutout-btn {\n cursor: pointer;\n opacity: 0.7;\n transition: opacity 0.15s, transform 0.15s;\n}\n\n.iwb-cutout-btn:hover {\n opacity: 1;\n transform: scale(1.15);\n}\n\n.iwb-cutout-btn svg {\n width: 14px;\n height: 14px;\n display: block;\n}\n\n/* 正在处理中的按钮状态 */\n.iwb-cutout-btn.processing {\n animation: iwb-cutout-pulse 1s infinite;\n pointer-events: none;\n}\n\n@keyframes iwb-cutout-pulse {\n 0%, 100% { opacity: 0.4; }\n 50% { opacity: 1; }\n}\n\n/* 全屏遮罩 */\n.iwb-cutout-overlay {\n position: fixed;\n top: 0;\n left: 0;\n width: 100%;\n height: 100%;\n background: rgba(0, 0, 0, 0.25);\n display: none;\n align-items: center;\n justify-content: center;\n flex-direction: column;\n gap: 12px;\n z-index: 999999;\n pointer-events: all;\n backdrop-filter: blur(2px);\n}\n\n/* 自定义按钮提示(挂在 body,最高层级,不会被图片遮挡) */\n#iwb-cutout-tip {\n position: fixed;\n z-index: 2147483647;\n background: rgba(30, 30, 46, 0.95);\n color: #fff;\n padding: 5px 10px;\n border-radius: 6px;\n font-size: 12px;\n line-height: 1.5;\n white-space: nowrap;\n pointer-events: none;\n display: none;\n box-shadow: 0 2px 8px rgba(0, 0, 0, 0.35);\n border: 1px solid rgba(255, 255, 255, 0.14);\n font-family: system-ui, -apple-system, "Segoe UI", sans-serif;\n max-width: 320px;\n white-space: normal;\n word-break: break-all;\n}\n\n/* 加载动画 */\n.iwb-cutout-spinner {\n width: 48px;\n height: 48px;\n border: 4px solid rgba(255, 255, 255, 0.3);\n border-top-color: #e8a735;\n border-radius: 50%;\n animation: iwb-cutout-spin 0.8s linear infinite;\n}\n\n@keyframes iwb-cutout-spin {\n to { transform: rotate(360deg); }\n}\n\n/* 遮罩文字 */\n.iwb-cutout-text {\n color: #fff;\n font-size: 14px;\n font-weight: 500;\n text-shadow: 0 1px 3px rgba(0, 0, 0, 0.5);\n background: rgba(0, 0, 0, 0.6);\n padding: 8px 16px;\n border-radius: 6px;\n}\n\n/* Toast 提示 */\n.iwb-cutout-toast {\n position: fixed;\n bottom: 24px;\n left: 50%;\n transform: translateX(-50%);\n padding: 10px 20px;\n border-radius: 8px;\n font-size: 13px;\n font-weight: 500;\n z-index: 999999;\n transition: opacity 0.3s;\n box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);\n display: none;\n max-width: 400px;\n}\n\n.iwb-cutout-toast-success {\n background: #1a7f37;\n color: #fff;\n}\n\n.iwb-cutout-toast-error {\n background: #cf222e;\n color: #fff;\n}\n\n.iwb-cutout-toast-info {\n background: #1f6feb;\n color: #fff;\n}\n\n/* 白底按钮 */\n.iwb-whitebg-btn {\n cursor: pointer;\n opacity: 0.7;\n transition: opacity 0.15s, transform 0.15s;\n}\n.iwb-whitebg-btn:hover { opacity: 1; transform: scale(1.15); }\n.iwb-whitebg-btn svg { width: 14px; height: 14px; display: block; }\n.iwb-whitebg-btn.processing { animation: iwb-cutout-pulse 1s infinite; pointer-events: none; }\n\n/* 编辑按钮 */\n.iwb-editor-btn-icon {\n cursor: pointer;\n opacity: 0.7;\n transition: opacity 0.15s, transform 0.15s;\n}\n.iwb-editor-btn-icon:hover { opacity: 1; transform: scale(1.15); }\n.iwb-editor-btn-icon svg { width: 14px; height: 14px; display: block; }\n\n/* ==================== 图片编辑器 ==================== */\n\n.iwb-editor-overlay {\n position: fixed;\n top: 0; left: 0;\n width: 100%; height: 100%;\n background: rgba(0, 0, 0, 0.6);\n display: none;\n align-items: center;\n justify-content: center;\n z-index: 999998;\n backdrop-filter: blur(3px);\n}\n\n.iwb-editor-modal {\n background: #1e1e2e;\n border-radius: 0;\n box-shadow: none;\n display: flex;\n flex-direction: column;\n width: 100vw;\n height: 100vh;\n max-width: none;\n max-height: none;\n overflow: visible;\n}\n\n/* 新增:主区域(画布 + 图层面板)flex 布局 */\n.iwb-editor-main {\n display: flex;\n flex: 1 1 auto;\n min-height: 0;\n overflow: visible;\n}\n\n.iwb-editor-header {\n display: flex;\n align-items: center;\n gap: 12px;\n padding: 10px 16px;\n background: #181825;\n border-bottom: 1px solid #313244;\n flex-wrap: nowrap;\n}\n.iwb-editor-header > .iwb-editor-tools {\n position: absolute;\n left: 12px;\n top: 68px;\n width: 44px;\n flex-direction: column;\n padding: 6px;\n background: #181825;\n border: 1px solid #313244;\n border-radius: 8px;\n z-index: 20;\n}\n.iwb-editor-header > .iwb-editor-tools .iwb-editor-action { position: static; }\n.iwb-editor-header > .iwb-editor-tools .iwb-editor-action[data-action="undo"],\n.iwb-editor-header > .iwb-editor-tools .iwb-editor-action[data-action="redo"],\n.iwb-editor-header > .iwb-editor-tools .iwb-editor-action[data-action="reset"],\n.iwb-editor-header > .iwb-editor-tools .iwb-editor-action[data-action="restore"] {\n position: absolute;\n top: -54px;\n left: auto;\n}\n.iwb-editor-header > .iwb-editor-tools .iwb-editor-action[data-action="undo"] { right: 154px; }\n.iwb-editor-header > .iwb-edLine truncated
// image-annotate/plugin/glue.js
function createGlue(ctx, css) {
+4 -1
View File
@@ -93,7 +93,10 @@ check('从真实 KV 加载并启用(SRI 通过)', Boolean(active), JSON.stri
check('线上版本 = package.json(' + WANT_VERSION + ')', Boolean(active && active.version === WANT_VERSION), active && active.version)
const scripts = await page.evaluate(() => Array.from(document.querySelectorAll('script[src*="/plugins/"]')).map((s) => ({ src: s.getAttribute('src'), integrity: s.getAttribute('integrity') || '' })))
check('插件脚本用 SRI(sha256) 加载', scripts.some((s) => /^\/plugins\/plugin-image-annotate\.[a-f0-9]{12}\.js$/.test(s.src) && /^sha256-/.test(s.integrity)), JSON.stringify(scripts))
// 文件名两种都合法:plugins-publish.mjs 产内容寻址名(.<hash12>.js,可 immutable 缓存),
// plugins-publish.sh(带主干守卫的合规通道)产固定名(plugin-image-annotate.js,走 no-cache+ETag)。
// 断言的关键是「必须带 integrity」,与命名策略无关。
check('插件脚本用 SRI(sha256) 加载', scripts.some((s) => /^\/plugins\/plugin-image-annotate(\.[a-f0-9]{12})?\.js$/.test(s.src) && /^sha256-/.test(s.integrity)), JSON.stringify(scripts))
// ---------- 2) 打开工作区 + 节点存在 ----------
await page.locator('.iwb-home-card:not(.iwb-home-new)').first().dblclick()
+151
View File
@@ -1360,6 +1360,157 @@ check('图层不透明度:Ctrl+Z 回到 100%,画面同步', await (async ()
: 'opacity=' + (l && l.opacity) + ' css=' + (l && l.cssOpacity)
})())
// ---------- v1.8 快速效果:参数可调 ----------
// 造一个确定有内容的层(空层做效果没有可比像素)
await page.keyboard.press('Control+Shift+n')
await page.waitForTimeout(180)
const fxLayerId = (await dbg()).activeLayerId
await page.locator('.iwb-editor-tool[data-tool="brush"]').click()
await page.locator('.iwb-editor-optionbar-body input.iwb-opt-num[data-opt="brushSize"]').fill('60')
await drag2(liveBox.x + liveBox.width * 0.2, liveBox.y + liveBox.height * 0.3,
liveBox.x + liveBox.width * 0.8, liveBox.y + liveBox.height * 0.7)
await page.waitForTimeout(200)
const fxHash = () => page.evaluate((id) => window.__iwbEditor.__debug().layerHash(id), fxLayerId)
const fxSet = async (v) => {
await page.evaluate((val) => {
const el = document.querySelector('.iwb-editor-fx-range')
if (!el) return
el.value = String(val)
el.dispatchEvent(new Event('input', { bubbles: true }))
el.dispatchEvent(new Event('change', { bubbles: true }))
}, v)
await page.waitForTimeout(90)
}
check('快速效果:点马赛克后参数滑杆启用,单位是块大小', await (async () => {
const h0 = (await dbg()).history
await page.locator('[data-fx="mosaic"]').click()
await page.waitForTimeout(260)
const d = await dbg()
const range = page.locator('.iwb-editor-fx-range')
if (!d.fx.hasSource || d.fx.key !== 'mosaic') return 'fx=' + JSON.stringify(d.fx)
if (await range.isDisabled()) return '滑杆仍禁用'
const min = await range.getAttribute('min')
const max = await range.getAttribute('max')
const name = (await page.locator('.iwb-editor-fx-adj-name').textContent()) || ''
const val = (await page.locator('.iwb-editor-fx-adj-val').textContent()) || ''
if (min !== '2' || max !== '96') return 'range=' + min + '~' + max
if (name.indexOf('马赛克') < 0 || name.indexOf('块大小') < 0) return '标签=' + name
if (val.indexOf('px') < 0) return '数值=' + val
if (d.history - h0 !== 1) return '撤销条数=' + (d.history - h0) + '(点效果应只拍 1 张)'
return true
})())
check('马赛克:块 12 → 48 → 12 与首次 12 完全一致(从基准重算,不叠加)', await (async () => {
await fxSet(12)
const h12a = await fxHash()
await fxSet(48)
const h48 = await fxHash()
await fxSet(12)
const h12b = await fxHash()
if (!h12a) return '指纹读取失败'
if (h12a === h48) return '块大小变化没有改变像素'
if (h12a !== h12b) return '12px 两次结果不同,发生叠加: ' + h12a + ' vs ' + h12b
return true
})())
check('效果参数:连续拖动不新增撤销记录', await (async () => {
const h0 = (await dbg()).history
for (const v of [20, 36, 60]) await fxSet(v)
const h1 = (await dbg()).history
return h1 === h0 ? true : '撤销 ' + h0 + '→' + h1
})())
check('反白:50% 各通道趋近 128,100% 彻底反向(强度真的生效)', await (async () => {
await page.locator('[data-fx="invert"]').click()
await page.waitForTimeout(240)
await fxSet(50)
const c50 = await page.evaluate((id) => window.__iwbEditor.__debug().avgColor(id), fxLayerId)
await fxSet(100)
const c100 = await page.evaluate((id) => window.__iwbEditor.__debug().avgColor(id), fxLayerId)
if (!c50 || !c100) return '取色失败'
const near128 = c50.slice(0, 3).every(v => Math.abs(v - 128) <= 5)
if (!near128) return '50%=' + c50.slice(0, 3).join(',')
if (!(c100[0] <= 12 && c100[1] >= 160)) return '100%=' + c100.slice(0, 3).join(',')
return true
})())
check('同一效果再点=回默认参数,且不新增撤销记录', await (async () => {
await page.locator('[data-fx="mosaic"]').click()
await page.waitForTimeout(220)
await fxSet(64)
const before = await fxHash()
const h0 = (await dbg()).history
await page.locator('[data-fx="mosaic"]').click()
await page.waitForTimeout(260)
const d = await dbg()
const after = await fxHash()
if (d.history !== h0) return '撤销 +' + (d.history - h0)
if (before === after) return '点第二次毫无变化(应回默认块大小)'
return d.fx.key === 'mosaic' && d.fx.value !== 64 ? true : 'value=' + d.fx.value
})())
check('切到别的层:效果滑杆置灰;切回原层恢复可调', await (async () => {
await page.keyboard.press('Control+Shift+n')
await page.waitForTimeout(240)
const off = await page.locator('.iwb-editor-fx-range').isDisabled()
await page.locator('.iwb-layer-item[data-layer-id="' + fxLayerId + '"]').click()
await page.waitForTimeout(240)
const on = !(await page.locator('.iwb-editor-fx-range').isDisabled())
return off && on ? true : '切走禁用=' + off + ' 切回恢复=' + on
})())
check('形状控制点屏幕尺寸恒定(不随图片放大而膨胀)', await (async () => {
// 当前这张 96×64 的图被「适应窗口」放大 ~9 倍。旧实现按 5.5 / S.zoom 画,
// 屏幕尺寸实际是 11 * fitW/imgW ≈ 100px(截图里那种巨大发光点);
// 现在按 viewScale() 换算,应稳定在 11px 左右、与图片尺寸无关。
await page.locator('[data-tool="rect"]').click()
const b = await page.locator('.iwb-editor-layer-canvas').first().boundingBox()
await page.mouse.move(b.x + b.width * 0.25, b.y + b.height * 0.25)
await page.mouse.down()
await page.mouse.move(b.x + b.width * 0.75, b.y + b.height * 0.75, { steps: 6 })
await page.mouse.up()
await page.waitForTimeout(320)
const sizes = await page.evaluate(() => {
const oc = document.querySelector('.iwb-editor-crop-overlay')
const rect = oc.getBoundingClientRect()
const sw = Math.max(1, Math.round(rect.width)), sh = Math.max(1, Math.round(rect.height))
// 重采样到屏幕尺寸:overlay 内部是图片坐标,小图上控制点在画布里只有 1~2px
const tmp = document.createElement('canvas')
tmp.width = sw; tmp.height = sh
const t = tmp.getContext('2d')
t.imageSmoothingEnabled = false
t.drawImage(oc, 0, 0, sw, sh)
const d = t.getImageData(0, 0, sw, sh).data
const seen = new Uint8Array(sw * sh)
const white = (i) => d[i * 4] > 235 && d[i * 4 + 1] > 235 && d[i * 4 + 2] > 235 && d[i * 4 + 3] > 200
const out = []
for (let i = 0; i < sw * sh; i++) {
if (seen[i] || !white(i)) continue
const st = [i]; seen[i] = 1
let mnx = 1e9, mxx = -1, mny = 1e9, mxy = -1, n = 0
while (st.length) {
const p = st.pop(); const px = p % sw, py = (p - px) / sw; n++
if (px < mnx) mnx = px
if (px > mxx) mxx = px
if (py < mny) mny = py
if (py > mxy) mxy = py
for (const q of [p - 1, p + 1, p - sw, p + sw]) {
if (q < 0 || q >= sw * sh || seen[q]) continue
const qx = q % sw
if (Math.abs(qx - px) > 1) continue
if (white(q)) { seen[q] = 1; st.push(q) } else seen[q] = 1
}
}
if (n >= 25) out.push(Math.round(((mxx - mnx) + (mxy - mny)) / 2))
}
return out
})
const max = sizes.length ? Math.max(...sizes) : 0
return sizes.length >= 4 && max <= 16 ? true : '控制点屏幕尺寸=' + JSON.stringify(sizes)
})())
check('无选中时 Ctrl+] 有 toast 提示(不再无声失败)', await (async () => {
await page.keyboard.press('Escape') // 清掉可能残留的选中态
await page.keyboard.press('Control+]')