Compare commits

..
Author SHA1 Message Date
qiqi 040b08fe28 fix(image-annotate): v1.8.3 图层不透明度滑杆可拖动、图层拖动排序真正生效
- 去掉图层项的 HTML5 draggable(它会把子元素的原生拖动一起接管,
  滑杆因此只能点不能拖)
- 排序改为指针拖动:越过行中线就实时插位,松手读 DOM 顺序落地,
  修掉「向下拖一格索引回退等于原地不动」
- 拖动中整行浮起、其余行让位;原图固定最底层;滑块拖动像素实时跟随
- blur 兜底必须判 e.target === window,否则子元素失焦会取消拖动
- harness 新增 6 项(真实鼠标拖滑杆 / 换位与 z / 拖到最底 /
  位移不足算点击 / 焦点在工具栏时也能拖 / 位图与矢量混排),共 146 项
2026-11-08 19:27:09 +08:00
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
16 changed files with 865 additions and 217 deletions

No files matched your search

+67
View File
@@ -234,6 +234,73 @@ P 下双击 = 结束当前路径(`commitPenPath`),不再进节点编辑。
- 文字 / 形状 / 钢笔会被直接栅格化进结果层(PS 合并矢量层也是这个结果)。
- 结果层落回「原最低参与层」的位置,`assignLayerZ` 重新连续编号,不产生重复 z。
## v1.8.3:图层面板交互修复(滑杆能拖、图层能拖排)
线上两个反馈,根子在同一个属性上:
1. **不透明度滑杆只能点、不能拖** —— 点了滑杆轨道数值会跳,但按住拖动毫无反应。
2. **图层拖不动排序** —— 拖了松手顺序不变,看起来像没实现。
### 根因
图层项写了 `draggable="true"`。HTML5 原生拖动是**祖先级**的:在任何子元素上按住拖动,
浏览器会先把它当成「拖动这个祖先」,于 range 滑杆的拇指永远收不到拖动事件(只剩点击能改值)。
排序那套 `dragstart/drop` 本身能跑,但插入位置按「目标项索引」算 ——
先把自己从数组里删掉再取目标索引,向下拖一格时索引正好回退,结果等于原地不动;
加上没有任何落点反馈(`.drop-target` 样式写了却没人加),最终观感就是「拖了没反应」。
### 修法
- **整项去掉 `draggable`**,排序改由 `bindLayerDragSort()` 用指针事件自己实现:
`pointerdown` 记录起点 → 位移超 4px 才算拖动(否则仍是一次点击选中)→
`pointermove` 越过哪一行的中线就真的 `insertBefore` 到那一行前面,其余行实时让位 →
`pointerup` 直接读 DOM 顺序落地。
- **不再自己算索引**:落点顺序就是最终 DOM 顺序,从根上消掉「上下方向语义不一致」这类错。
- **滑杆/按钮/改名输入框不参与排序**(`closest` 排除),拖动滑杆时图层像素实时跟随(CSS `opacity`)。
- 一次拖动 = 一条撤销;顺序没变则不拍快照、不留空撤销。
- `原图` 固定最底层:拖到最底只能停在它上面,不会被拖到看不见的地方。
- 拖动中整行浮起(描橙边、不透明,避免与下方行文字叠成一团),列表光标 `grabbing`。
### 一个必须记住的坑
`window.addEventListener('blur', …, true)` **会收到子元素的 blur**(blur 不冒泡但捕获能收)。
用它做「窗口失焦就取消拖动」的兜底时,鼠标一按到图层行、焦点从工具栏按钮挪走就会立刻
取消这次拖动 —— 表现为「先点过按钮再拖必然失败」。必须判 `e.target === window`。
harness 里专门有一条用例守着它。
测试:`node image-annotate/tools/harness.mjs` 146 项(新增 6 项:真实鼠标拖滑杆、
向下换位与 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 不符或加载失败)」,插件直接不可用。
+1
View File
@@ -124,6 +124,7 @@
| 无混合模式 | 正片叠底/滤色/叠加是合成常用 | P3 |
| 无图层蒙版 | 抠图只能破坏性擦除,不能反悔 | P3 |
| ~~无重命名 / 多选~~ / 编组 | ✅ v1.7:双击名字改名(自算双击)、⌘/Ctrl 点击多选合并;编组仍待做 | 部分完成 |
| ~~拖动排序不生效~~ | ✅ v1.8.3:整项 `draggable` 会吃掉子元素的原生拖动(滑杆只能点不能拖)、向下拖一格索引回退等于原地不动。改为指针拖动 + 实时插位,松手读 DOM 顺序落地 | 已完成 |
| `resetDraw()` 语义歧义 | 「清空标注」只清非 base 层像素,留下空白粘贴层(1.0.5 遗留)⇒ **已裁定改为「全部还原」**:删所有非 base 层 + 清绘制 + 复位变换,一步可撤销;按钮改名「还原原图」 | P0 定语义(已定) |
### 3.4 输出(单张)
+1 -1
View File
@@ -1,7 +1,7 @@
{
"name": "@iwb-plugin/image-annotate",
"private": true,
"version": "1.8.1",
"version": "1.8.3",
"description": "IWB 插件:图片标注 / 修图(编辑器移植自 iwb-plaus 扩展,纯 Canvas 2D)",
"ibwPlugin": {
"id": "image-annotate",
+16 -4
View File
@@ -751,6 +751,8 @@
flex: 1 1 auto;
overflow-y: auto;
padding: 4px;
/* 拖动排序的插入线是绝对定位的,锚点必须在列表上(随滚动一起移动) */
position: relative;
}
/* 图层项:整项改成「行 + 可选的不透明度行」,两行都靠 .iwb-layer-row 保持原来的横向排布 */
@@ -758,7 +760,8 @@
display: block;
padding: 5px 8px;
border-radius: 6px;
cursor: pointer;
cursor: grab;
user-select: none;
transition: background 0.12s;
margin-bottom: 2px;
}
@@ -774,9 +777,18 @@
box-shadow: inset 2px 0 0 #e8a735;
}
.iwb-layer-item.hidden { opacity: 0.5; }
.iwb-layer-item[draggable="true"] { cursor: grab; }
.iwb-layer-item.dragging { opacity: 0.45; }
.iwb-layer-item.drop-target { outline: 1px dashed #e8a735; background: rgba(232, 167, 53, 0.16); }
/* 拖动中:整行跟着指针浮起,压住相邻行;其余行由 JS 实时让位(落点反馈) */
.iwb-layer-item.dragging {
position: relative;
z-index: 3;
opacity: 1;
background: #3a3d55;
box-shadow: 0 6px 18px rgba(0, 0, 0, 0.5), inset 0 0 0 1px #e8a735;
transition: none;
cursor: grabbing;
}
.iwb-editor-layer-list.sorting,
.iwb-editor-layer-list.sorting .iwb-layer-item { cursor: grabbing; }
/* 画笔/橡皮作用目标:与「选中」分离,避免出现两个图层同时高亮 */
.iwb-layer-paint { flex: 0 0 auto; color: #a6adc8; font-size: 11px; opacity: 0.85; }
/* 不透明度角标:只有非 100% 才出现,一眼看出哪层被调淡了 */
+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]
+6 -5
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'
@@ -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() }
}
+3 -3
View File
@@ -32,6 +32,7 @@ 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'
@@ -139,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)
}
}
+197 -28
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])
@@ -611,10 +612,13 @@ export function setActiveLayer(id) {
// 免得窄面板里「名字 + ✎ + 角标 + 锁 + 删除」把图层名挤成几个字
const pct = opacityPct(item.opacity)
const canRename = item.type === 'bitmap'
html += `<div class="iwb-layer-item${activeClass}${multiClass}${visClass}" draggable="${item.id !== 'base'}" data-layer-id="${item.id}" data-layer-type="${item.type}">
// 注意:整项不能用 HTML5 draggable —— 它会把子元素上的原生拖动一起接管,
// 不透明度滑杆因此「只能点、不能拖」。排序改由 bindLayerDragSort 自己实现。
const sortHint = item.id === 'base' ? '原图(固定在最底层)' : '拖动调整叠放顺序'
html += `<div class="iwb-layer-item${activeClass}${multiClass}${visClass}" data-layer-id="${item.id}" data-layer-type="${item.type}">
<div class="iwb-layer-row">
<button class="iwb-layer-vis" data-vis-id="${item.id}" data-vis-type="${item.type}" title="${item.visible ? '隐藏' : '显示'}">${visSvg}</button>
<span class="iwb-layer-thumb"><canvas width="44" height="44" data-thumb-id="${item.id}" data-thumb-type="${item.type}"></canvas><span class="iwb-layer-icon">${typeIconSvg}</span></span>
<span class="iwb-layer-thumb" title="${sortHint}"><canvas width="44" height="44" data-thumb-id="${item.id}" data-thumb-type="${item.type}"></canvas><span class="iwb-layer-icon">${typeIconSvg}</span></span>
<span class="iwb-layer-name${canRename ? ' renamable' : ''}" data-name-id="${item.id}" data-name-type="${item.type}" title="${esc(item.name)}${canRename ? ' · 双击重命名' : ''}">${esc(item.name)}</span>
${item.paintTarget ? '<span class="iwb-layer-paint" title="当前画笔 / 橡皮作用图层">✎</span>' : ''}
${(pct < 100 && !item.active) ? `<span class="iwb-layer-op" title="不透明度 ${pct}%(选中该层可调)">${pct}%</span>` : ''}
@@ -645,25 +649,185 @@ export function setActiveLayer(id) {
bindLayerPanelEvents()
}
function reorderPanelItem(dragId, targetId) {
if (!dragId || !targetId || dragId === targetId || dragId === 'base' || targetId === 'base') return
const all = layerUnits()
const baseIdx = all.findIndex(u => u.obj.id === 'base')
if (baseIdx > 0) { const [b] = all.splice(baseIdx, 1); all.unshift(b) }
const from = all.findIndex(item => item.obj.id === dragId)
const to0 = all.findIndex(item => item.obj.id === targetId)
if (from < 0 || to0 < 0) return
const before = all.map(u => u.obj.id).join('|')
const [moved] = all.splice(from, 1)
const to = Math.max(all.findIndex(item => item.obj.id === targetId), baseIdx >= 0 ? 1 : 0)
all.splice(to, 0, moved)
if (all.map(u => u.obj.id).join('|') === before) return
saveSnapshot()
assignLayerZ(all)
/**
* 把图层面板的顺序(降序展示 = 最上层在前)算成目标 z 序。
* 单独抽出来是因为「拖动排序」和「面板顺序」必须共用同一套写入路径:
* 面板倒序 → z 升序由 layerUnits() 的排序保证,这里只按面板倒序反转后重排。
*
* 任何单元对不上(图层在拖动期间被删/被合并)就整体放弃,宁可不排序也不能丢层。
* @param {string[]} descKeys 「类型:id」组成的降序数组
* @returns {{ordered: Array, changed: boolean}|null} 无法安全重排时返回 null
*/
function planPanelOrder(descKeys) {
const units = layerUnits() // z 升序
const byKey = new Map(units.map(u => [u.kind + ':' + u.obj.id, u]))
const ordered = []
for (const key of descKeys.slice().reverse()) {
const u = byKey.get(key)
if (!u) continue
byKey.delete(key)
ordered.push(u)
}
if (!ordered.length || byKey.size) return null
// 原图永远压在最底层:它被合进画面底图,跑到别的层上面只会让人以为图没了
const baseIdx = ordered.findIndex(u => u.obj.id === 'base')
if (baseIdx > 0) { const [b] = ordered.splice(baseIdx, 1); ordered.unshift(b) }
const before = units.map(u => u.obj.id).join('|')
return { ordered, changed: before !== ordered.map(u => u.obj.id).join('|') }
}
/** 落地面板顺序:只有顺序真的变了才拍快照 + 重排,空拖动不留无效撤销。
* 无论走哪条分支都必须重绘面板 —— 调用方(拖动排序)在此之前已经改过 DOM 次序。 */
function applyPanelOrder(descKeys) {
const plan = planPanelOrder(descKeys)
if (!plan || !plan.changed) { renderLayerPanel(); return false }
saveSnapshot('调整图层顺序')
assignLayerZ(plan.ordered)
reorderLayerCanvas()
sortLayersByZ()
renderObjects()
renderLayerPanel()
return true
}
// ---------- 拖动排序(指针事件,替代原来的 HTML5 draggable) ----------
// v1.8.3 老实现的三个硬伤:
// 1) 整项 draggable 会把子元素上的原生拖动一起接管 —— 不透明度滑杆于是只能点、不能拖;
// 2) 插入位置按「目标项索引」算,向下拖一格时先删自己再取索引会回退,等于原地不动;
// 3) 只有 .dragging 半透明,没有任何落点反馈,看起来像没反应。
// 现在:行跟着指针浮动(transform 位移),越过谁的中线就真的插到谁前面,
// 其余行实时让位;松手时直接读 DOM 顺序落地,不再自己算索引。
const SORT_THRESHOLD = 4 // 位移超过 4px 才算拖动,否则仍然是一次点击
let _sortDrag = null
function bindLayerDragSort(list) {
if (list._iwbSortBound) return
list._iwbSortBound = true
list.addEventListener('pointerdown', (e) => {
if (e.button !== 0 || _sortDrag) return
const item = e.target.closest('.iwb-layer-item')
if (!item || !list.contains(item)) return
if (item.dataset.layerId === 'base') return // 原图固定最底
// 控件、不透明度滑杆行、改名输入框都不参与排序:
// 否则滑杆刚按下就被判成「拖图层」,又回到只能点不能拖的老问题
if (e.target.closest('.iwb-layer-op-row, input, button, .iwb-layer-name-input')) return
_sortDrag = {
list, item,
id: item.dataset.layerId, type: item.dataset.layerType,
startY: e.clientY, y: e.clientY,
pointerId: e.pointerId, active: false
}
document.addEventListener('pointermove', onSortMove, true)
document.addEventListener('pointerup', onSortEnd, true)
document.addEventListener('pointercancel', onSortCancel, true)
// 兜底:切窗口时 pointerup 可能永远不来,不收拾干净的话下一次按下会被
// _sortDrag 挡住,整个排序从此失效。
// 注意 blur 不冒泡但**会**被捕获阶段收到(聚焦的按钮/输入框失焦也算),
// 所以必须判 target 是不是 window 本身 —— 否则鼠标一按在图层行上,
// 焦点从工具栏挪走就会立刻把这次拖动取消掉(踩过一次)。
window.addEventListener('blur', onWindowBlur, true)
})
}
function onSortMove(e) {
const d = _sortDrag
if (!d) return
if (e.pointerId != null && d.pointerId != null && e.pointerId !== d.pointerId) return
d.y = e.clientY
if (!d.active) {
if (Math.abs(e.clientY - d.startY) < SORT_THRESHOLD) return
const rect = d.item.getBoundingClientRect()
d.grabY = e.clientY - rect.top // 抓取点在行内的偏移,浮动时保持手感
d.active = true
d.list.classList.add('sorting')
d.item.classList.add('dragging')
// 拖过图层名就算拖排序了,别让之前那次按下残留成「双击改名」的第一次点击
S.lastNameClick = null
}
updateSortTarget(d)
}
function updateSortTarget(d) {
const list = d.list
const lr = list.getBoundingClientRect()
// 贴近上下边缘时自动滚动,长列表也能一路拖到底
if (d.y < lr.top + 18) list.scrollTop -= 8
else if (d.y > lr.bottom - 18) list.scrollTop += 8
// 落点:指针越过哪一行的中线,就把自己挪到那一行之前(原图永远最后)
const rows = Array.from(list.querySelectorAll('.iwb-layer-item'))
const baseEl = rows.find(el => el.dataset.layerId === 'base') || null
const movable = rows.filter(el => el !== baseEl && el !== d.item)
let anchor = baseEl || null // 默认落到最底(原图之上)
for (const el of movable) {
const r = el.getBoundingClientRect()
if (d.y < r.top + r.height / 2) { anchor = el; break }
}
if (d.item.nextElementSibling !== anchor || d.item.parentNode !== list) {
// 真的搬 DOM:其余行当场让位,这就是最直观的落点反馈
if (anchor) list.insertBefore(d.item, anchor)
else list.appendChild(d.item)
}
// 搬完之后让行继续贴着指针:先清 transform 量出它在新位置的顶边,再补回位移
d.item.style.transform = ''
const r = d.item.getBoundingClientRect()
const dy = Math.round(d.y - d.grabY - r.top)
d.item.style.transform = dy ? 'translateY(' + dy + 'px)' : ''
}
/** 松手:直接读 DOM 顺序落地(顺序已经在这之前实时调整好了) */
function onSortEnd(e) {
const d = _sortDrag
if (!d) return
if (e && e.pointerId != null && d.pointerId != null && e.pointerId !== d.pointerId) return
cleanupSortDrag()
if (!d.active) return // 没越过阈值:当成普通点击,走原来的选中逻辑
const rows = Array.from(d.list.querySelectorAll('.iwb-layer-item'))
const keyOf = (el) => el.dataset.layerType + ':' + el.dataset.layerId
const baseEl = rows.find(el => el.dataset.layerId === 'base') || null
const desc = rows.filter(el => el !== baseEl).map(keyOf)
if (baseEl) desc.push(keyOf(baseEl))
// 拖动即选中:拖完直接能在下面调不透明度/继续操作,不用再点一次
if (d.type === 'bitmap') {
if (S.layers.some(l => l.id === d.id)) S.selectedLayerId = d.id
} else if (d.type === 'text' || d.type === 'shape') {
selectUnit(d.type, d.id)
}
// 落地(含「顺序没变」的面板刷新)全在 applyPanelOrder 里,它会整块重绘
applyPanelOrder(desc)
}
/** 指针被系统打断(触摸手势 / 浏览器抢事件):放弃这次拖动,顺序回到拖动前 */
function onSortCancel(e) {
const d = _sortDrag
if (!d) return
if (e && e.pointerId != null && d.pointerId != null && e.pointerId !== d.pointerId) return
const wasActive = d.active
cleanupSortDrag()
if (wasActive) renderLayerPanel()
}
/** 只有「窗口本身失焦」才算打断;子元素失焦的 blur 也会被捕获到,必须滤掉 */
function onWindowBlur(e) {
if (e.target !== window && e.target !== document) return
onSortCancel(null)
}
function cleanupSortDrag() {
const d = _sortDrag
if (!d) return
document.removeEventListener('pointermove', onSortMove, true)
document.removeEventListener('pointerup', onSortEnd, true)
document.removeEventListener('pointercancel', onSortCancel, true)
window.removeEventListener('blur', onWindowBlur, true)
_sortDrag = null
d.list.classList.remove('sorting')
d.item.classList.remove('dragging')
d.item.style.transform = ''
}
function bindLayerPanelEvents() {
@@ -671,6 +835,7 @@ export function setActiveLayer(id) {
if (!list) return
bindLayerItemEvents(list)
bindLayerDragSort(list)
bindLayerNameRename(list)
bindLayerOpacityInputs(list)
bindLayerVisButtons(list)
@@ -678,15 +843,11 @@ export function setActiveLayer(id) {
bindLayerDelButtons(list)
}
/** 图层面板项:点击选中(位图/文字/形状)+ 拖到另一项上排序 */
/** 图层面板项:点击选中(位图/文字/形状)+ 指针拖动排序(见 bindLayerDragSort) */
function bindLayerItemEvents(list) {
// 点击图层项 → 设为活跃
list.querySelectorAll('.iwb-layer-item').forEach(item => {
item.addEventListener('mousedown', (e) => e.stopPropagation())
item.addEventListener('dragstart', (e) => { if (item.draggable) { e.dataTransfer.setData('text/plain', item.dataset.layerId); item.classList.add('dragging') } })
item.addEventListener('dragend', () => item.classList.remove('dragging'))
item.addEventListener('dragover', (e) => { if (item.draggable) e.preventDefault() })
item.addEventListener('drop', (e) => { e.preventDefault(); reorderPanelItem(e.dataTransfer.getData('text/plain'), item.dataset.layerId) })
item.addEventListener('click', (e) => {
if (e.target.closest('.iwb-layer-vis') || e.target.closest('.iwb-layer-lock') || e.target.closest('.iwb-layer-del')) return
// 拖动不透明度滑杆 / 正在改名:都不能触发整块重绘,否则控件节点会被换掉
@@ -752,8 +913,7 @@ export function setActiveLayer(id) {
input.value = layer.name
input.maxLength = 40
span.replaceWith(input)
// 重命名期间禁用整项拖动,否则在输入框里拖选文字会变成拖动图层排序
item.draggable = false
// 输入框本身被拖动排序逻辑排除(input 选择器),在框里拖选文字不会变成拖图层
let done = false
const finish = (commit) => {
@@ -791,13 +951,22 @@ export function setActiveLayer(id) {
// 双击滑块复位 100%(PS 里双击「不透明度」标题即可复位,这里沿用同一习惯)
input.addEventListener('dblclick', (e) => {
e.stopPropagation()
input._opSnapTaken = false
input.value = '100'
applyOpacityFromInput(input)
input._opSnapTaken = false
})
input.addEventListener('input', (e) => {
e.stopPropagation()
applyOpacityFromInput(input)
})
// 一次拖动 / 一次方向键操作结束后重开快照闸门:
// 否则滑杆在面板重绘前一直复用一个标记,第二次拖动就不再记撤销了
const resetSnap = () => { input._opSnapTaken = false }
input.addEventListener('change', resetSnap)
input.addEventListener('pointerup', resetSnap)
input.addEventListener('pointercancel', resetSnap)
input.addEventListener('blur', resetSnap)
})
}
+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)) {
+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'
+239 -111
View File
@@ -9,7 +9,7 @@
var __IWB_ANNOTATE_MANIFEST__ = {
id: 'image-annotate',
name: '标注 / 修图',
version: '1.8.1',
version: '1.8.3',
apiVersion: 1,
capabilities: ['commands', 'nodeActions', 'canvas', 'canvasWrite'],
settings: {
@@ -176,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);
@@ -262,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],
@@ -294,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) {
@@ -313,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],
@@ -643,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();
@@ -930,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];
@@ -968,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;
@@ -981,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;
@@ -995,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--) {
@@ -1155,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);
@@ -1207,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);
@@ -1225,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);
@@ -1246,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();
}
@@ -1258,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]);
@@ -1267,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);
@@ -1309,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);
@@ -1375,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;
}
@@ -1391,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]]);
@@ -1402,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++) {
@@ -1642,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],
@@ -1722,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]);
@@ -2103,10 +2116,11 @@ var __IWB_ANNOTATE_MANIFEST__ = {
const delSvg = '<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round"><line x1="18" y1="6" x2="6" y2="18"/><line x1="6" y1="6" x2="18" y2="18"/></svg>';
const pct = opacityPct(item.opacity);
const canRename = item.type === "bitmap";
html += `<div class="iwb-layer-item${activeClass}${multiClass}${visClass}" draggable="${item.id !== "base"}" data-layer-id="${item.id}" data-layer-type="${item.type}">
const sortHint = item.id === "base" ? "原图(固定在最底层)" : "拖动调整叠放顺序";
html += `<div class="iwb-layer-item${activeClass}${multiClass}${visClass}" data-layer-id="${item.id}" data-layer-type="${item.type}">
<div class="iwb-layer-row">
<button class="iwb-layer-vis" data-vis-id="${item.id}" data-vis-type="${item.type}" title="${item.visible ? "隐藏" : "显示"}">${visSvg}</button>
<span class="iwb-layer-thumb"><canvas width="44" height="44" data-thumb-id="${item.id}" data-thumb-type="${item.type}"></canvas><span class="iwb-layer-icon">${typeIconSvg}</span></span>
<span class="iwb-layer-thumb" title="${sortHint}"><canvas width="44" height="44" data-thumb-id="${item.id}" data-thumb-type="${item.type}"></canvas><span class="iwb-layer-icon">${typeIconSvg}</span></span>
<span class="iwb-layer-name${canRename ? " renamable" : ""}" data-name-id="${item.id}" data-name-type="${item.type}" title="${esc(item.name)}${canRename ? " · 双击重命名" : ""}">${esc(item.name)}</span>
${item.paintTarget ? '<span class="iwb-layer-paint" title="当前画笔 / 橡皮作用图层">✎</span>' : ""}
${pct < 100 && !item.active ? `<span class="iwb-layer-op" title="不透明度 ${pct}%(选中该层可调)">${pct}%</span>` : ""}
@@ -2129,33 +2143,154 @@ var __IWB_ANNOTATE_MANIFEST__ = {
}
bindLayerPanelEvents();
}
function reorderPanelItem(dragId, targetId) {
if (!dragId || !targetId || dragId === targetId || dragId === "base" || targetId === "base") return;
const all = layerUnits();
const baseIdx = all.findIndex((u) => u.obj.id === "base");
if (baseIdx > 0) {
const [b] = all.splice(baseIdx, 1);
all.unshift(b);
function planPanelOrder(descKeys) {
const units = layerUnits();
const byKey = new Map(units.map((u) => [u.kind + ":" + u.obj.id, u]));
const ordered = [];
for (const key of descKeys.slice().reverse()) {
const u = byKey.get(key);
if (!u) continue;
byKey.delete(key);
ordered.push(u);
}
const from = all.findIndex((item) => item.obj.id === dragId);
const to0 = all.findIndex((item) => item.obj.id === targetId);
if (from < 0 || to0 < 0) return;
const before = all.map((u) => u.obj.id).join("|");
const [moved] = all.splice(from, 1);
const to = Math.max(all.findIndex((item) => item.obj.id === targetId), baseIdx >= 0 ? 1 : 0);
all.splice(to, 0, moved);
if (all.map((u) => u.obj.id).join("|") === before) return;
saveSnapshot();
assignLayerZ(all);
if (!ordered.length || byKey.size) return null;
const baseIdx = ordered.findIndex((u) => u.obj.id === "base");
if (baseIdx > 0) {
const [b] = ordered.splice(baseIdx, 1);
ordered.unshift(b);
}
const before = units.map((u) => u.obj.id).join("|");
return { ordered, changed: before !== ordered.map((u) => u.obj.id).join("|") };
}
function applyPanelOrder(descKeys) {
const plan = planPanelOrder(descKeys);
if (!plan || !plan.changed) {
renderLayerPanel();
return false;
}
saveSnapshot("调整图层顺序");
assignLayerZ(plan.ordered);
reorderLayerCanvas();
sortLayersByZ();
renderObjects();
renderLayerPanel();
return true;
}
var SORT_THRESHOLD = 4;
var _sortDrag = null;
function bindLayerDragSort(list) {
if (list._iwbSortBound) return;
list._iwbSortBound = true;
list.addEventListener("pointerdown", (e) => {
if (e.button !== 0 || _sortDrag) return;
const item = e.target.closest(".iwb-layer-item");
if (!item || !list.contains(item)) return;
if (item.dataset.layerId === "base") return;
if (e.target.closest(".iwb-layer-op-row, input, button, .iwb-layer-name-input")) return;
_sortDrag = {
list,
item,
id: item.dataset.layerId,
type: item.dataset.layerType,
startY: e.clientY,
y: e.clientY,
pointerId: e.pointerId,
active: false
};
document.addEventListener("pointermove", onSortMove, true);
document.addEventListener("pointerup", onSortEnd, true);
document.addEventListener("pointercancel", onSortCancel, true);
window.addEventListener("blur", onWindowBlur, true);
});
}
function onSortMove(e) {
const d = _sortDrag;
if (!d) return;
if (e.pointerId != null && d.pointerId != null && e.pointerId !== d.pointerId) return;
d.y = e.clientY;
if (!d.active) {
if (Math.abs(e.clientY - d.startY) < SORT_THRESHOLD) return;
const rect = d.item.getBoundingClientRect();
d.grabY = e.clientY - rect.top;
d.active = true;
d.list.classList.add("sorting");
d.item.classList.add("dragging");
S.lastNameClick = null;
}
updateSortTarget(d);
}
function updateSortTarget(d) {
const list = d.list;
const lr = list.getBoundingClientRect();
if (d.y < lr.top + 18) list.scrollTop -= 8;
else if (d.y > lr.bottom - 18) list.scrollTop += 8;
const rows = Array.from(list.querySelectorAll(".iwb-layer-item"));
const baseEl = rows.find((el) => el.dataset.layerId === "base") || null;
const movable = rows.filter((el) => el !== baseEl && el !== d.item);
let anchor = baseEl || null;
for (const el of movable) {
const r2 = el.getBoundingClientRect();
if (d.y < r2.top + r2.height / 2) {
anchor = el;
break;
}
}
if (d.item.nextElementSibling !== anchor || d.item.parentNode !== list) {
if (anchor) list.insertBefore(d.item, anchor);
else list.appendChild(d.item);
}
d.item.style.transform = "";
const r = d.item.getBoundingClientRect();
const dy = Math.round(d.y - d.grabY - r.top);
d.item.style.transform = dy ? "translateY(" + dy + "px)" : "";
}
function onSortEnd(e) {
const d = _sortDrag;
if (!d) return;
if (e && e.pointerId != null && d.pointerId != null && e.pointerId !== d.pointerId) return;
cleanupSortDrag();
if (!d.active) return;
const rows = Array.from(d.list.querySelectorAll(".iwb-layer-item"));
const keyOf = (el) => el.dataset.layerType + ":" + el.dataset.layerId;
const baseEl = rows.find((el) => el.dataset.layerId === "base") || null;
const desc = rows.filter((el) => el !== baseEl).map(keyOf);
if (baseEl) desc.push(keyOf(baseEl));
if (d.type === "bitmap") {
if (S.layers.some((l) => l.id === d.id)) S.selectedLayerId = d.id;
} else if (d.type === "text" || d.type === "shape") {
selectUnit(d.type, d.id);
}
applyPanelOrder(desc);
}
function onSortCancel(e) {
const d = _sortDrag;
if (!d) return;
if (e && e.pointerId != null && d.pointerId != null && e.pointerId !== d.pointerId) return;
const wasActive = d.active;
cleanupSortDrag();
if (wasActive) renderLayerPanel();
}
function onWindowBlur(e) {
if (e.target !== window && e.target !== document) return;
onSortCancel(null);
}
function cleanupSortDrag() {
const d = _sortDrag;
if (!d) return;
document.removeEventListener("pointermove", onSortMove, true);
document.removeEventListener("pointerup", onSortEnd, true);
document.removeEventListener("pointercancel", onSortCancel, true);
window.removeEventListener("blur", onWindowBlur, true);
_sortDrag = null;
d.list.classList.remove("sorting");
d.item.classList.remove("dragging");
d.item.style.transform = "";
}
function bindLayerPanelEvents() {
const list = runtime.el.querySelector(".iwb-editor-layer-list");
if (!list) return;
bindLayerItemEvents(list);
bindLayerDragSort(list);
bindLayerNameRename(list);
bindLayerOpacityInputs(list);
bindLayerVisButtons(list);
@@ -2165,20 +2300,6 @@ var __IWB_ANNOTATE_MANIFEST__ = {
function bindLayerItemEvents(list) {
list.querySelectorAll(".iwb-layer-item").forEach((item) => {
item.addEventListener("mousedown", (e) => e.stopPropagation());
item.addEventListener("dragstart", (e) => {
if (item.draggable) {
e.dataTransfer.setData("text/plain", item.dataset.layerId);
item.classList.add("dragging");
}
});
item.addEventListener("dragend", () => item.classList.remove("dragging"));
item.addEventListener("dragover", (e) => {
if (item.draggable) e.preventDefault();
});
item.addEventListener("drop", (e) => {
e.preventDefault();
reorderPanelItem(e.dataTransfer.getData("text/plain"), item.dataset.layerId);
});
item.addEventListener("click", (e) => {
if (e.target.closest(".iwb-layer-vis") || e.target.closest(".iwb-layer-lock") || e.target.closest(".iwb-layer-del")) return;
if (e.target.closest(".iwb-layer-opacity") || e.target.closest(".iwb-layer-name-input") || e.target.closest(".iwb-layer-op-row")) return;
@@ -2230,7 +2351,6 @@ var __IWB_ANNOTATE_MANIFEST__ = {
input.value = layer.name;
input.maxLength = 40;
span.replaceWith(input);
item.draggable = false;
let done = false;
const finish = (commit) => {
if (done) return;
@@ -2264,13 +2384,22 @@ var __IWB_ANNOTATE_MANIFEST__ = {
input.addEventListener("click", (e) => e.stopPropagation());
input.addEventListener("dblclick", (e) => {
e.stopPropagation();
input._opSnapTaken = false;
input.value = "100";
applyOpacityFromInput(input);
input._opSnapTaken = false;
});
input.addEventListener("input", (e) => {
e.stopPropagation();
applyOpacityFromInput(input);
});
const resetSnap = () => {
input._opSnapTaken = false;
};
input.addEventListener("change", resetSnap);
input.addEventListener("pointerup", resetSnap);
input.addEventListener("pointercancel", resetSnap);
input.addEventListener("blur", resetSnap);
});
}
function applyOpacityFromInput(input) {
@@ -2553,28 +2682,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;
@@ -3670,14 +3797,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();
@@ -3739,7 +3866,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));
@@ -3871,7 +3998,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;
@@ -4043,7 +4170,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();
}
@@ -5652,11 +5779,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 });
@@ -5679,7 +5808,6 @@ var __IWB_ANNOTATE_MANIFEST__ = {
clearOverlay();
S.pickerComposite = null;
renderObjects();
computeFit();
S.viewX = null;
applyView();
renderLayerPanel();
@@ -5693,11 +5821,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) {
@@ -5707,7 +5837,6 @@ var __IWB_ANNOTATE_MANIFEST__ = {
}
S.pickerComposite = null;
clearOverlay();
computeFit();
S.viewX = null;
applyView();
renderObjects();
@@ -5807,7 +5936,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];
@@ -5815,7 +5944,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;
}
@@ -5824,10 +5953,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";
@@ -5953,12 +6082,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;
@@ -5987,8 +6116,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);
@@ -6008,11 +6137,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);
@@ -6027,7 +6156,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];
@@ -6916,10 +7045,9 @@ 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() {
@@ -7151,7 +7279,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) {
+198
View File
@@ -1360,6 +1360,122 @@ check('图层不透明度:Ctrl+Z 回到 100%,画面同步', await (async ()
: 'opacity=' + (l && l.opacity) + ' css=' + (l && l.cssOpacity)
})())
// ---------- v1.8.3 图层面板交互:滑杆真能拖 + 图层真能拖排 ----------
// 面板顺序(最上层在前)与每层 id,供排序用例断言
const panelIds = () => page.evaluate(() => [...document.querySelectorAll('.iwb-layer-item')].map(el => el.dataset.layerId))
const zOf = (id) => page.evaluate((lid) => {
const d = window.__iwbEditor.__debug()
const l = d.layers.find(x => x.id === lid)
return l ? l.z : null
}, id)
/** 真实鼠标把第 from 行拖到第 to 行中线之上/之下(below=true 表示越过中线) */
async function dragRow(from, to, below = true) {
const a = page.locator('.iwb-layer-item').nth(from)
const b = page.locator('.iwb-layer-item').nth(to)
const ba = await a.boundingBox()
const bb = await b.boundingBox()
const x = ba.x + 44 // 落在缩略图/名字区域,避开左侧显示按钮
const y = ba.y + 10 // 行首部:选中行的下半截是不透明度滑杆,别往那儿按
await page.mouse.move(x, y)
await page.mouse.down()
await page.mouse.move(x, y + 8, { steps: 3 }) // 先越过 4px 阈值
await page.mouse.move(bb.x + 44, below ? bb.y + bb.height - 3 : bb.y + 3, { steps: 10 })
await page.mouse.up()
await page.waitForTimeout(200)
}
check('图层不透明度:真实鼠标拖动滑块,数值与画面一路跟随(不再只能点)', await (async () => {
await page.keyboard.press('Control+Shift+n')
await page.waitForTimeout(180)
const id = (await dbg()).activeLayerId
const box = await page.locator('.iwb-layer-item[data-layer-id="' + id + '"] .iwb-layer-opacity').boundingBox()
if (!box) return '选中项下没有不透明度滑杆'
const y = box.y + box.height / 2
// 从 85% 处按下,连续拖到 20%:被整项 draggable 抢事件时只有按下那一下生效,之后纹丝不动
await page.mouse.move(box.x + box.width * 0.85, y)
await page.mouse.down()
const seen = []
for (const f of [0.7, 0.5, 0.35, 0.2]) {
await page.mouse.move(box.x + box.width * f, y, { steps: 4 })
const l = (await dbg()).layers.find(x => x.id === id)
seen.push(l ? l.opacity : -1)
}
await page.mouse.up()
await page.waitForTimeout(120)
const l = (await dbg()).layers.find(x => x.id === id)
if (!l) return '图层丢失'
const follows = seen.every((v, i) => i === 0 || v < seen[i - 1] - 0.01)
if (!follows) return '拖动中数值没跟随 ' + JSON.stringify(seen.map(v => Math.round(v * 100)))
if (!(l.opacity < 0.35)) return '最终 opacity=' + l.opacity
if (Math.abs(l.cssOpacity - l.opacity) > 0.001) return '画面没跟上 css=' + l.cssOpacity
return true
})())
check('图层拖动排序:向下拖过下一行中线真的换位,z 同步、一次拖动一条撤销', await (async () => {
// 保证至少 3 个可移动层,才有「换位」可看
while ((await panelIds()).length < 4) {
await page.keyboard.press('Control+Shift+n')
await page.waitForTimeout(140)
}
const before = await panelIds()
const movedId = before[0], targetId = before[1]
const h0 = (await dbg()).history
await dragRow(0, 1, true)
const after = await panelIds()
if (after[0] !== targetId || after[1] !== movedId) return '没换位 ' + before.join(',') + ' → ' + after.join(',')
const zMoved = await zOf(movedId), zTarget = await zOf(targetId)
if (!(zMoved < zTarget)) return 'z 没同步 moved=' + zMoved + ' target=' + zTarget
const h1 = (await dbg()).history
if (h1 - h0 !== 1) return '撤销条数=' + (h1 - h0) + '(一次拖动应只拍 1 张快照)'
await page.keyboard.press('Control+z')
await page.waitForTimeout(280)
const back = await panelIds()
return back.join(',') === before.join(',') ? true : 'Ctrl+Z 未复原 ' + back.join(',')
})())
check('图层拖动排序:拖到最底停在「原图」之上,原图永远压在最底层', await (async () => {
const before = await panelIds()
const movedId = before[0]
const baseKey = before[before.length - 1]
if (baseKey !== 'base') return '原图不在面板最底:' + before.join(',')
await dragRow(0, before.length - 1, true) // 一路拖到底(原图那一行)
const after = await panelIds()
if (after[after.length - 1] !== 'base') return '原图没留在最底 ' + after.join(',')
if (after[after.length - 2] !== movedId) return '没落到原图之上 ' + after.join(',')
const zBase = await zOf('base')
return zBase === 0 ? true : '原图 z=' + zBase + '(应恒为 0)'
})())
check('图层拖动排序:位移不足 4px 算点击(不误判成拖动,顺序不变)', await (async () => {
const before = await panelIds()
const a = await page.locator('.iwb-layer-item').nth(0).boundingBox()
await page.mouse.move(a.x + 44, a.y + a.height / 2)
await page.mouse.down()
await page.mouse.move(a.x + 44, a.y + a.height / 2 + 2, { steps: 2 })
await page.mouse.up()
await page.waitForTimeout(160)
const after = await panelIds()
if (after.join(',') !== before.join(',')) return '顺序被改 ' + before.join(',') + ' → ' + after.join(',')
// 顺手确认这次按下仍然完成了「选中该层」
const sel = await page.evaluate(() => window.__iwbEditor.__debug().selectedLayerId)
return sel === before[0] ? true : '没选中 selectedLayerId=' + sel
})())
check('图层拖动排序:焦点在工具栏按钮上时也能拖(blur 兜底不误伤拖动)', await (async () => {
// 回归:window 捕获阶段的 blur 会连子元素失焦一起收到 —— 鼠标一按到图层行,
// 焦点从工具栏按钮挪走就会立刻把这次拖动取消。这条用例专门守住那个坑。
await page.locator('.iwb-editor-tool[data-tool="brush"]').click()
await page.waitForTimeout(80)
const before = await panelIds()
await dragRow(0, 1, true)
const after = await panelIds()
await page.locator('.iwb-editor-tool[data-tool="select"]').click()
return after[0] === before[1] && after[1] === before[0]
? true
: '没换位 ' + before.join(',') + ' → ' + after.join(',')
})())
// ---------- v1.8 快速效果:参数可调 ----------
// 造一个确定有内容的层(空层做效果没有可比像素)
await page.keyboard.press('Control+Shift+n')
@@ -1461,6 +1577,88 @@ check('切到别的层:效果滑杆置灰;切回原层恢复可调', await (
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('图层拖动排序:位图与矢量混排也能拖(面板顺序、z、DOM 叠放三者一致)', await (async () => {
// 位图和矢量走的是两套画布,排序落地后必须同时刷新 z 与 canvas-stack 的插入次序
await page.locator('.iwb-editor-tool[data-tool="rect"]').click()
await drag2(liveBox.x + liveBox.width * 0.2, liveBox.y + liveBox.height * 0.2,
liveBox.x + liveBox.width * 0.45, liveBox.y + liveBox.height * 0.45)
await page.waitForTimeout(240)
const rows = await page.evaluate(() => [...document.querySelectorAll('.iwb-layer-item')]
.map(el => el.dataset.layerType + ':' + el.dataset.layerId))
const shapeKey = rows.find(k => k.indexOf('shape:') === 0)
if (!shapeKey) return '没造出形状图层'
if (rows[0] !== shapeKey) return '新形状不在面板最上层 ' + rows.join(',')
await dragRow(0, rows.length - 1, true) // 一路拖到最底
const rows2 = await page.evaluate(() => [...document.querySelectorAll('.iwb-layer-item')]
.map(el => el.dataset.layerType + ':' + el.dataset.layerId))
if (rows2[rows2.length - 1] !== 'bitmap:base') return '原图没留在最底 ' + rows2.join(',')
if (rows2[rows2.length - 2] !== shapeKey) return '形状没落到原图之上 ' + rows2.join(',')
const geo = await page.evaluate(() => {
const d = window.__iwbEditor.__debug()
const sh = d.shapes[d.shapes.length - 1]
// canvas-stack 里矢量画布排在第几个(自底向上),应与 z 一致
const nodes = [...document.querySelectorAll('.iwb-editor-canvas-stack > canvas')]
const vecIdx = nodes.findIndex(n => n.className.indexOf('iwb-editor-vec-canvas') >= 0)
return { z: sh ? sh.z : null, baseZ: d.layers.find(l => l.id === 'base').z, vecIdx }
})
await page.locator('.iwb-editor-tool[data-tool="select"]').click()
if (geo.baseZ !== 0) return '原图 z=' + geo.baseZ
if (geo.z !== 1) return '形状 z=' + geo.z + '(应紧贴原图 = 1)'
return geo.vecIdx >= 1 ? true : '矢量画布在 DOM 里排到了最底 vecIdx=' + geo.vecIdx
})())
check('无选中时 Ctrl+] 有 toast 提示(不再无声失败)', await (async () => {
await page.keyboard.press('Escape') // 清掉可能残留的选中态
await page.keyboard.press('Control+]')