Files
iwb-plugins-desktop/image-annotate/src/index.js
T
qiqi 73a29715d3 fix(image-annotate): v1.9.1 文字输入框贴住点击点、选区图标归位、底色一选就生效
1) 输入框偏到左上:showTextInput 用 canvasStack 的矩形换算,但 stack 尺寸是
(imgW + 2*overlayPad)*scale、图片在 stack 内还偏移 pad*scale(图层 canvas 的
left/top)。比例偏小又漏偏移,两个误差同向叠加。改用 textCanvas 的矩形
(与图层 canvas 同基准,精确等于图片显示区域),并按 textarea 的边框 2px +
内边距 8/4px 反向偏移,让输入框里的文字起点正压在点击点上;提交后
drawTextObject 也从 t.x/t.y 起画,所见即所得。

2) 选「选择」工具后三个选区图标不见了:两处叠加。
   - selCmdHTML 排在 hint 之后,而 .iwb-opt-hint 带 margin-left:auto;
   - 更关键的是 .iwb-opt-sep 写成 margin: 0 4px 0 auto,分隔线自带 auto,
     会把分隔线之后的内容整组推到最右,选项栏排满时直接滚出可视区。
修法:分隔线只分组(margin: 0 2px),留白交给末尾 hint;选区按钮排在 hint 之前。
现在「文字」「选择」两个工具下都是同一组三个图标,未选中元素时也在。

3) 设了底色看不到:底色一直在画,只是「只改颜色没点开关」时 bgFill 仍是 false。
   - 改 bgColor 时自动打开 bgFill,按钮 active 同步;
   - 顺带修掉更硬的 bug:「底色」按钮只能开不能关 —— data-value 在生成 HTML 时
     写死,状态变了没人更新,每次点都传「开启」。改由 syncOptionBar 按当前状态翻面;
   - 默认底色透明度 0.55 → 0.68(浅色/花色底图上 0.55 太透,容易被当成没生效)。

harness 158 → 162 条全通(新增输入框落点误差 ≤3px、Esc 不留空对象、
选择工具未选中仍有 3 个图标、只选颜色即自动开底色);validate 9/9。
2026-11-08 20:53:58 +08:00

7992 lines
377 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
// 手写 manifest —— 必须保持单引号:scripts/validate.mjs 只认单引号形式,而 esbuild 打印器会改成双引号,
// 所以本文件不经 esbuild 转换,由 build-plugin.mjs 原样放在产物最前面(banner)。
//
// 为什么必须排在最前:校验器用「文件里第一个形如 id 冒号 单引号 的字面量」判定插件 id,
// 排在 bundle 之前才能保证取到的是下面这份 manifest,而不是打包代码里的同形字面量。
// ⚠️ 因此本文件的注释里不要写出那种字面量形态(会抢先匹配),要描述就直接说「id 字面量」。
//
// 版本占位符由构建脚本用 package.json 的 version 替换,保证两处永不漂移。
var __IWB_ANNOTATE_MANIFEST__ = {
id: 'image-annotate',
name: '标注 / 修图',
version: '1.9.1',
apiVersion: 1,
capabilities: ['commands', 'nodeActions', 'canvas', 'canvasWrite'],
settings: {
exportPreset: { type: 'string', default: 'original' },
exportFormat: { type: 'string', default: 'png' },
exportBg: { type: 'string', default: 'transparent' },
exportMaxKB: { type: 'number', default: 0 },
exportSize: { type: 'number', default: 800 },
panelsCollapsed: { type: 'boolean', default: false }
},
}
"use strict";
(() => {
// image-annotate/plugin/editor/state.js
var ZOOM_MIN = 0.1;
var ZOOM_MAX = 10;
var ZOOM_STEP = 1.15;
var S = {
open: false,
tool: "brush",
color: "#ff4444",
brushSize: 3,
brushHardness: 100,
// 画笔硬度 0~100:100=硬边描边,<100=径向渐变软边章
brushOpacity: 1,
// 画笔透明度 0.05~1(一笔整体透明度,笔划内不叠加)
prevTool: null,
// 吸管工具激活前的工具(取色后切回)
// 画布内最后一次悬停点(图片坐标):用 [ ] 调笔刷大小时要按这个点立刻重画笔刷环,
// 否则光标环会停在旧尺寸,直到用户再动一下鼠标才更新(v1.6)
hoverPos: null,
lastClick: null,
// 上一次画布按下 {t,x,y}:自算双击用(dblclick 在画布上不可靠)
// 上一次点击图层名 {id,t}:图层面板重命名也走自算双击(点一下就会重绘面板,
// 浏览器不会在同一个节点上派发 dblclick)
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 工具参数解耦:形状线宽与文字字号不再借用画笔粗细,
// 否则「调细画笔」会顺手把所有形状的描边一起改掉。
shapeLineWidth: 3,
// 矩形/圆形/箭头/钢笔的描边粗细
shapeRadius: 0,
// 矩形圆角半径 px(v1.9,仅 rect 有意义)
textSize: 32,
// 新建文字的字号 px
// ---- v1.9 文字样式:这套是「新建文字」的默认值,每段文字自己存一份 ----
textWeight: "bold",
// bold | normal | 900
textAlign: "left",
// left | center | right(多行时各行按块宽对齐)
textLineHeight: 1.25,
// 行高倍数(1.25 = 老版单行高度,勿随意改)
textStrokeWidth: 0,
// 描边宽度 px,0 = 无描边
textStrokeColor: "#ffffff",
textBgFill: false,
// 底色块
textBgColor: "#000000",
// 最近使用颜色(最多 8 个,存 ctx.settings,跨会话保留)
recentColors: [],
// 图层系统
layers: [],
// 位图图层数组 [{ id, name, canvas, ctx, opacity, visible, z }]
activeLayerId: null,
// 当前活跃位图图层 ID(画笔/橡皮操作目标)
// 画布引用(动态创建的 canvas 元素)
canvasWrap: null,
canvasStack: null,
textCanvas: null,
strokeCanvas: null,
overlayCanvas: null,
textCtx: null,
strokeCtx: null,
overlayCtx: null,
isDrawing: false,
panning: false,
panStart: null,
startX: 0,
startY: 0,
history: [],
redoStack: [],
cropRect: null,
cropHandle: null,
cropMoving: false,
moveStart: null,
cropConstraint: { type: "free", ratio: 0, sizeW: 0, sizeH: 0 },
// 文字图层(独立对象,可选中/移动/缩放/再编辑)
textLayers: [],
// [{ id, x, y, text, color, fontSize, opacity, visible, z }]
selectedTextId: null,
textDrag: null,
// { mode:'move'|'scale', start:{x,y}, layer:{x,y}, fontSize, baseX }
textEditingId: null,
selectedLayerId: null,
// 选择工具当前选中的可编辑位图图层
// 图层多选集合 [{id,type}](v1.6):只为「合并选中图层」服务,
// 不参与单选语义(selectedLayerId / selectedTextId 仍各管各的)。
layerMulti: [],
bitmapDrag: null,
// { mode:'move'|'scale', handle, start, layer, pending }
// 形状图层(矩形/箭头,独立对象,可选中/移动/调手柄)
shapeLayers: [],
// [{ id, type:'rect'|'arrow', x1,y1,x2,y2, color, lw, fill, opacity, visible, z }]
selectedShapeId: null,
shapeDrag: null,
// { mode:'move'|'handle', handle, start:{x,y}, shape:{...}, pending }
penPath: null,
// 钢笔绘制中的点序列与预览点
penEditId: null,
// 钢笔二次编辑中的形状 id
penDragPt: -1,
// 正在拖动的节点下标(-1=无)
penDragBase: null,
penDragPending: null,
zCounter: 0,
// 全局 z 序计数器(文字与形状统一排序)
// 图片放置中状态(导入图片时先调整大小/位置再确认)
placingImage: null,
// { img, x, y, w, h } 图片坐标
placingHandle: null,
// 'move' | 'nw'|'ne'|'sw'|'se'|'n'|'s'|'e'|'w'
placingStart: null,
// { mx, my, x, y, w, h }
imgW: 0,
imgH: 0,
overlayPad: 0,
originalImage: null,
// 打开时的原始图片,用于「复原」
fitW: 0,
fitH: 0,
// 适应容器时的基准显示尺寸
zoom: 1,
// 缩放倍率(基于 fit)
viewX: null,
// 画布平移位置(wrap 内 left;null = 居中显示)
viewY: null,
callbacks: null,
spaceDown: false,
_shiftDown: false,
_canvasEventsBound: false,
// ---- v1.1 选区 / 便利性 ----
selection: null,
// { kind, path, bbox, feather, active, fillRule, outline }
marquee: null,
// 拉框中的临时选区 { x0,y0,x1,y1,kind }
lassoPts: null,
// 套索绘制中的点序列
selectionKind: "rect",
// 选区工具的形状:rect | ellipse
selectionFeather: 0,
// 羽化 px(0~20)
selectionCanvas: null,
// 蚂蚁线专用层(与 overlay 分离,互不擦除)
selectionCtx: null,
cursorCanvas: null,
// 笔刷环专用层
cursorCtx: null,
_antFrame: 0,
// 蚂蚁线 rAF 句柄
_antOffset: 0,
exportOptions: null,
// { preset, format, bg, maxKB, size },来自 ctx.settings
interaction: "idle",
// 轻量交互状态机:idle | marquee | lasso | placing | cropping
renderAll: null,
// 由 index.js 注入的统一重绘出口
guides: null,
// 拖动吸附参考线(图片坐标,松手清空):[{axis:'x'|'y', at, from, to}]
lastExport: null
// 观测口:{ bytes, width, height, format, preset }
};
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);
const canvas = createLayerCanvas();
const ctx = canvas.getContext("2d", { willReadFrequently: true });
ctx.clearRect(0, 0, S.imgW, S.imgH);
const layer = {
id,
name: "图层 " + (S.layers.length + 1),
image: img,
x,
y,
w,
h,
rotation: rotation || 0,
transformable: true,
canvas,
ctx,
opacity: 1,
visible: true,
locked: false,
// 与矢量对象 / 空白图层共用同一个 z 计数器(旧值 S.layers.length 会和 ++S.zCounter 撞车,
// 导致粘贴的截图与图形 z 相同:排序按钮交换 z 无效、命中测试选错对象)
z: ++S.zCounter
};
redrawBitmapLayer(layer);
saveSnapshot();
S.layers.push(layer);
reorderLayerCanvas();
setActiveLayer(id);
updateLayerCanvasStyles();
renderLayerPanel();
return layer;
}
function confirmImagePlacement() {
if (!S.placingImage) return;
const { img, x, y, w, h } = S.placingImage;
const placementRotation = S.placingImage.rotation || 0;
S.placingImage = null;
S.placingHandle = null;
S.placingStart = null;
clearOverlay();
commitImageAsLayer(img, x, y, w, h, placementRotation);
updateCursor();
}
function placeImageDirectly(img) {
const iw = img.naturalWidth || img.width;
const ih = img.naturalHeight || img.height;
const ratio = Math.min(S.imgW * 0.5 / iw, S.imgH * 0.5 / ih, 1);
const w = Math.max(10, Math.round(iw * ratio));
const h = Math.max(10, Math.round(ih * ratio));
const layer = commitImageAsLayer(img, Math.round((S.imgW - w) / 2), Math.round((S.imgH - h) / 2), w, h, 0);
try {
if (document.activeElement && document.activeElement.blur) document.activeElement.blur();
} catch (e) {
}
if (S.renderAll) S.renderAll();
return layer;
}
function cancelImagePlacement() {
S.placingImage = null;
S.placingHandle = null;
S.placingStart = null;
clearOverlay();
updateCursor();
}
function drawPlacementPreview() {
if (!S.placingImage) return;
const ctx = S.overlayCtx;
const { img, x, y, w, h } = S.placingImage;
const rot = S.placingImage.rotation || 0;
const cx = x + w / 2, cy = y + h / 2;
clearOverlay();
ctx.save();
ctx.fillStyle = "rgba(0,0,0,0.35)";
ctx.fillRect(0, 0, S.imgW, S.imgH);
ctx.restore();
ctx.save();
ctx.translate(cx, cy);
if (rot) ctx.rotate(rot * Math.PI / 180);
ctx.translate(-cx, -cy);
ctx.drawImage(img, x, y, w, h);
ctx.restore();
const corners = boxCorners(x, y, w, h, rot);
ctx.save();
ctx.strokeStyle = "#4488ff";
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 / viewScale();
ctx.fillStyle = "#fff";
ctx.strokeStyle = "#4488ff";
ctx.lineWidth = 1.5 / viewScale();
const localPts = {
nw: [x, y],
ne: [x + w, y],
sw: [x, y + h],
se: [x + w, y + h],
n: [x + w / 2, y],
s: [x + w / 2, y + h],
e: [x + w, y + h / 2],
w: [x, y + h / 2]
};
for (const name in localPts) {
const ptp = rotPt(localPts[name][0], localPts[name][1], cx, cy, rot);
ctx.beginPath();
ctx.rect(ptp[0] - hs, ptp[1] - hs, hs * 2, hs * 2);
ctx.fill();
ctx.stroke();
}
ctx.restore();
drawRotationHandles(ctx, { x, y, w, h }, rot);
ctx.save();
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 / viewScale();
const tw = ctx.measureText(hintText).width;
ctx.fillStyle = "rgba(0,0,0,0.6)";
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 / viewScale());
ctx.restore();
}
function hitPlacementHandle(pos) {
if (!S.placingImage) return null;
const { x, y, w, h } = S.placingImage;
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 / viewScale();
if (hitRotationHandle(lp, { x, y, w, h })) return "rotate";
const pts = {
nw: [x, y],
ne: [x + w, y],
sw: [x, y + h],
se: [x + w, y + h],
n: [x + w / 2, y],
s: [x + w / 2, y + h],
e: [x + w, y + h / 2],
w: [x, y + h / 2]
};
let best = null, bestDist = 1e9;
for (const name in pts) {
const dx = lp[0] - pts[name][0], dy = lp[1] - pts[name][1];
const d = dx * dx + dy * dy;
if (d < R * R && d < bestDist) {
bestDist = d;
best = name;
}
}
return best;
}
function insidePlacementRect(pos) {
if (!S.placingImage) return false;
const { x, y, w, h } = S.placingImage;
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);
return lp[0] >= x && lp[0] <= x + w && lp[1] >= y && lp[1] <= y + h;
}
function resizePlacement(pos) {
if (!S.placingImage || !S.placingHandle || !S.placingStart) return;
const { img } = S.placingImage;
const s = S.placingStart;
const iw = img.naturalWidth || img.width;
const ih = img.naturalHeight || img.height;
const aspect = iw / ih;
const hh = S.placingHandle;
if (hh === "move") {
const dx = pos.x - s.mx;
const dy = pos.y - s.my;
S.placingImage.x = s.x + dx;
S.placingImage.y = s.y + dy;
return;
}
if (hh === "rotate") {
const rcx = s.x + s.w / 2, rcy = s.y + s.h / 2;
const a0 = Math.atan2(s.my - rcy, s.mx - rcx);
const a1 = Math.atan2(pos.y - rcy, pos.x - rcx);
let deg = (s.rotation || 0) + (a1 - a0) * 180 / Math.PI;
if (S._shiftDown) deg = Math.round(deg / 15) * 15;
S.placingImage.rotation = deg;
return;
}
const loc = unrotPt(pos.x, pos.y, s.x + s.w / 2, s.y + s.h / 2, s.rotation || 0);
pos = { x: loc[0], y: loc[1] };
let nx = s.x, ny = s.y, nw = s.w, nh = s.h;
if (hh.includes("e")) nw = Math.max(10, pos.x - s.x);
if (hh.includes("s")) nh = Math.max(10, pos.y - s.y);
if (hh.includes("w")) {
const r = s.x + s.w;
nx = Math.min(pos.x, r - 10);
nw = r - nx;
}
if (hh.includes("n")) {
const b = s.y + s.h;
ny = Math.min(pos.y, b - 10);
nh = b - ny;
}
if (S._shiftDown) {
if (nw / nh > aspect) {
if (hh.includes("n") || hh.includes("s")) {
nw = nh * aspect;
if (hh.includes("w")) nx = s.x + s.w - nw;
} else {
nh = nw / aspect;
if (hh.includes("n")) ny = s.y + s.h - nh;
}
} else {
if (hh.includes("e") || hh.includes("w")) {
nh = nw / aspect;
if (hh.includes("n")) ny = s.y + s.h - nh;
} else {
nw = nh * aspect;
if (hh.includes("w")) nx = s.x + s.w - nw;
}
}
}
S.placingImage.x = nx;
S.placingImage.y = ny;
S.placingImage.w = nw;
S.placingImage.h = nh;
}
// image-annotate/plugin/vendor/layer-logic.js
function isDrawableLayer(layer) {
return !!layer && layer.id !== "base" && !layer.image;
}
function restorePath(layer) {
if (!layer) return "pixels";
const sourceCanvas = isDrawableLayer(layer) ? null : layer.sourceCanvas;
if (layer.transformable && (layer.image || sourceCanvas)) return "redraw";
return "pixels";
}
function needsPixelSnapshot(layer) {
return restorePath(layer) === "pixels";
}
// image-annotate/plugin/vendor/image-math.js
function hexToRgb(hex) {
const h = String(hex || "").replace("#", "");
const v = h.length === 3 ? h.split("").map((c) => c + c).join("") : h;
return {
r: parseInt(v.slice(0, 2), 16) || 0,
g: parseInt(v.slice(2, 4), 16) || 0,
b: parseInt(v.slice(4, 6), 16) || 0
};
}
function rgbToHex(r, g, b) {
const to = (v) => Math.max(0, Math.min(255, Math.round(v))).toString(16).padStart(2, "0");
return `#${to(r)}${to(g)}${to(b)}`;
}
function parseRatio(str) {
if (str === "free" || !str) return 0;
const parts = String(str).split(":");
if (parts.length === 2) {
const w = parseFloat(parts[0]);
const h = parseFloat(parts[1]);
if (w > 0 && h > 0) return w / h;
}
return 0;
}
// image-annotate/plugin/editor/recent-colors.js
var MAX = 8;
var KEY = "recentColors";
function valid(hex) {
return /^#[0-9a-f]{6}$/i.test(String(hex || ""));
}
function loadRecentColors() {
const st = S.callbacks && S.callbacks.settings;
let list = [];
if (st && typeof st.get === "function") {
try {
const got = st.get(KEY);
if (Array.isArray(got)) list = got;
} catch (e) {
}
}
S.recentColors = list.filter(valid).map((c) => String(c).toLowerCase()).slice(0, MAX);
renderRecentColors();
}
function rememberColor(hex) {
if (!valid(hex)) return;
const c = String(hex).toLowerCase();
if (S.recentColors && S.recentColors[0] === c) return;
const list = [c].concat((S.recentColors || []).filter((x) => x !== c));
S.recentColors = list.slice(0, MAX);
const st = S.callbacks && S.callbacks.settings;
if (st && typeof st.set === "function") {
try {
st.set(KEY, S.recentColors);
} catch (e) {
}
}
renderRecentColors();
}
function renderRecentColors() {
const wrap = runtime.el && runtime.el.querySelector(".iwb-editor-recent-colors");
if (!wrap) return;
const list = S.recentColors || [];
wrap.innerHTML = list.map(
(c) => `<button type="button" class="iwb-editor-color-panel-swatch" data-panel-color="${c}" style="background:${c}" title="最近使用 ${c}"></button>`
).join("");
wrap.hidden = !list.length;
}
// image-annotate/plugin/editor/tools.js
var brushStampCache = { key: "", canvas: null };
function getBrushStamp(size, color, hardness) {
const key = size + "|" + color + "|" + hardness;
if (brushStampCache.key === key && brushStampCache.canvas) return brushStampCache.canvas;
const c = document.createElement("canvas");
c.width = size;
c.height = size;
const cx = c.getContext("2d");
const half = size / 2;
const { r, g, b } = hexToRgb(color);
const grad = cx.createRadialGradient(half, half, half * hardness / 100, half, half, half);
grad.addColorStop(0, `rgba(${r},${g},${b},1)`);
grad.addColorStop(1, `rgba(${r},${g},${b},0)`);
cx.fillStyle = grad;
cx.fillRect(0, 0, size, size);
brushStampCache = { key, canvas: c };
return c;
}
function strokeSegment(x1, y1, x2, y2) {
const ctx = S.strokeCtx;
const size = Math.max(1, S.brushSize);
const color = S.tool === "eraser" ? "#ffffff" : S.color;
ctx.save();
if (S.brushHardness >= 100) {
ctx.strokeStyle = color;
ctx.lineWidth = size;
ctx.lineCap = "round";
ctx.lineJoin = "round";
ctx.beginPath();
ctx.moveTo(x1, y1);
ctx.lineTo(x2, y2);
ctx.stroke();
} else {
const stamp = getBrushStamp(size, color, S.brushHardness);
const dist = Math.hypot(x2 - x1, y2 - y1);
const step = Math.max(1, size / 6);
const n = Math.max(0, Math.ceil(dist / step));
for (let i = 0; i <= n; i++) {
const t = n === 0 ? 0 : i / n;
ctx.drawImage(stamp, x1 + (x2 - x1) * t - size / 2, y1 + (y2 - y1) * t - size / 2);
}
}
ctx.restore();
S.strokeCanvas.style.opacity = S.brushOpacity;
}
function eraseSegment(x1, y1, x2, y2) {
const ctx = getActiveCtx();
if (!ctx) return;
ctx.save();
if (S.selection && S.selection.active) ctx.clip(S.selection.path, S.selection.fillRule);
ctx.globalCompositeOperation = "destination-out";
ctx.globalAlpha = S.brushOpacity;
ctx.lineWidth = Math.max(1, S.brushSize);
ctx.lineCap = "round";
ctx.lineJoin = "round";
ctx.beginPath();
ctx.moveTo(x1, y1);
ctx.lineTo(x2, y2);
ctx.stroke();
ctx.restore();
const active = getActiveLayer();
if (active && active.id === "draw" && active.sourceCanvas) {
const sourceCtx = active.sourceCanvas.getContext("2d", { willReadFrequently: true });
sourceCtx.save();
sourceCtx.globalCompositeOperation = "destination-out";
sourceCtx.globalAlpha = S.brushOpacity;
sourceCtx.lineWidth = Math.max(1, S.brushSize) * active.w / Math.max(S.imgW, 1);
sourceCtx.lineCap = "round";
sourceCtx.beginPath();
sourceCtx.moveTo((x1 - active.x) * S.imgW / active.w, (y1 - active.y) * S.imgW / active.w);
sourceCtx.lineTo((x2 - active.x) * S.imgW / active.w, (y2 - active.y) * S.imgW / active.w);
sourceCtx.stroke();
sourceCtx.restore();
}
S.pickerComposite = null;
renderObjects();
}
function bakeDrawableLayer(layer) {
if (!layer || !isDrawableLayer(layer) || !layer._srcBox) return;
layer._srcBox = null;
layer.sourceCanvas = null;
layer.rotation = 0;
layer.x = 0;
layer.y = 0;
layer.w = S.imgW;
layer.h = S.imgH;
layer._bounds = void 0;
}
function beginStroke() {
bakeDrawableLayer(getActiveLayer());
S.strokeCanvas.width = S.imgW;
S.strokeCanvas.height = S.imgH;
S.strokeCtx.clearRect(0, 0, S.imgW, S.imgH);
S.strokeCanvas.style.display = S.tool === "eraser" ? "none" : "block";
S.strokeCanvas.style.opacity = S.brushOpacity;
}
function endStroke() {
for (const l of S.layers) l._bounds = void 0;
const ctx = getActiveCtx();
if (!ctx) return;
ctx.save();
if (S.selection && S.selection.active) ctx.clip(S.selection.path, S.selection.fillRule);
if (S.tool === "eraser") {
ctx.globalCompositeOperation = "destination-out";
}
ctx.globalAlpha = S.brushOpacity;
ctx.drawImage(S.strokeCanvas, 0, 0);
ctx.restore();
S.strokeCanvas.style.display = "none";
const active = getActiveLayer();
if (active && active.id === "draw" && active.sourceCanvas && active.w > 0 && active.h > 0) {
const sourceCtx = active.sourceCanvas.getContext("2d", { willReadFrequently: true });
sourceCtx.save();
sourceCtx.globalCompositeOperation = S.tool === "eraser" ? "destination-out" : "source-over";
sourceCtx.globalAlpha = S.brushOpacity;
sourceCtx.translate(-active.x * S.imgW / active.w, -active.y * S.imgH / active.h);
sourceCtx.scale(S.imgW / active.w, S.imgH / active.h);
sourceCtx.drawImage(S.strokeCanvas, 0, 0);
sourceCtx.restore();
}
S.strokeCtx.clearRect(0, 0, S.imgW, S.imgH);
S.pickerComposite = null;
}
function roundedRadius(s, w, h) {
const r = Number(s && s.radius) || 0;
if (r <= 0) return 0;
return Math.min(r, Math.min(w, h) / 2);
}
function roundRectPath(ctx, x, y, w, h, r) {
const rr = Math.min(r, Math.min(w, h) / 2);
ctx.moveTo(x + rr, y);
ctx.arcTo(x + w, y, x + w, y + h, rr);
ctx.arcTo(x + w, y + h, x, y + h, rr);
ctx.arcTo(x, y + h, x, y, rr);
ctx.arcTo(x, y, x + w, y, rr);
ctx.closePath();
}
function drawShape(ctx, s) {
ctx.save();
ctx.globalAlpha = s.opacity != null ? s.opacity : 1;
const rot = s.rotation || 0;
if (rot) {
const b = shapeBounds(s);
const cx = b.x + b.w / 2, cy = b.y + b.h / 2;
ctx.translate(cx, cy);
ctx.rotate(rot * Math.PI / 180);
ctx.translate(-cx, -cy);
}
ctx.strokeStyle = s.color;
ctx.lineWidth = s.lw;
ctx.lineCap = "round";
ctx.lineJoin = "round";
if (s.type === "pen") {
const pts = Array.isArray(s.pts) ? s.pts : [];
if (pts.length > 1) {
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);
if (s.closed) ctx.closePath();
if (s.closed && s.fill) {
ctx.fillStyle = s.color;
ctx.fill();
}
ctx.stroke();
}
} else if (s.type === "rect") {
const rx = Math.min(s.x1, s.x2), ry = Math.min(s.y1, s.y2), rw = Math.abs(s.x2 - s.x1), rh = Math.abs(s.y2 - s.y1);
const radius = roundedRadius(s, rw, rh);
if (radius > 0) {
ctx.beginPath();
roundRectPath(ctx, rx, ry, rw, rh, radius);
if (s.fill) {
ctx.fillStyle = s.color;
ctx.fill();
}
ctx.stroke();
} else {
if (s.fill) {
ctx.fillStyle = s.color;
ctx.fillRect(rx, ry, rw, rh);
}
ctx.strokeRect(rx, ry, rw, rh);
}
} else if (s.type === "circle") {
const rx = Math.min(s.x1, s.x2), ry = Math.min(s.y1, s.y2);
const rw = Math.abs(s.x2 - s.x1), rh = Math.abs(s.y2 - s.y1);
ctx.beginPath();
ctx.ellipse(rx + rw / 2, ry + rh / 2, Math.max(1, rw / 2), Math.max(1, rh / 2), 0, 0, Math.PI * 2);
if (s.fill) {
ctx.fillStyle = s.color;
ctx.fill();
}
ctx.stroke();
} else {
ctx.fillStyle = s.color;
ctx.beginPath();
ctx.moveTo(s.x1, s.y1);
ctx.lineTo(s.x2, s.y2);
ctx.stroke();
const angle = Math.atan2(s.y2 - s.y1, s.x2 - s.x1);
const headLen = Math.max(12, s.lw * 4);
ctx.beginPath();
ctx.moveTo(s.x2, s.y2);
ctx.lineTo(s.x2 - headLen * Math.cos(angle - Math.PI / 6), s.y2 - headLen * Math.sin(angle - Math.PI / 6));
ctx.moveTo(s.x2, s.y2);
ctx.lineTo(s.x2 - headLen * Math.cos(angle + Math.PI / 6), s.y2 - headLen * Math.sin(angle + Math.PI / 6));
ctx.stroke();
}
ctx.restore();
}
function getToolBrushRadius() {
return Math.max(1, S.brushSize) / 2;
}
function screenScale() {
const rect = S.canvasStack.getBoundingClientRect();
return rect.width ? rect.width / S.imgW : S.zoom;
}
function clearToolRing() {
const ctx = S.cursorCtx;
if (!ctx) return;
ctx.save();
ctx.setTransform(1, 0, 0, 1, 0, 0);
ctx.clearRect(0, 0, ctx.canvas.width, ctx.canvas.height);
ctx.restore();
resetOverlayTransform(ctx);
}
function drawToolRing(pos) {
clearToolRing();
const ctx = S.cursorCtx || S.overlayCtx;
const r = getToolBrushRadius();
const k = 1 / screenScale();
const rMin = 2 * k;
const rr = Math.max(r, rMin);
ctx.save();
ctx.lineWidth = k;
ctx.strokeStyle = "rgba(0,0,0,0.8)";
ctx.beginPath();
ctx.arc(pos.x, pos.y, rr, 0, Math.PI * 2);
ctx.stroke();
ctx.strokeStyle = "rgba(255,255,255,0.9)";
ctx.lineWidth = k;
ctx.beginPath();
ctx.arc(pos.x, pos.y, Math.max(rr - k, 0), 0, Math.PI * 2);
ctx.stroke();
ctx.restore();
}
function getCompositeCanvas() {
const c = document.createElement("canvas");
c.width = S.imgW;
c.height = S.imgH;
const cx = c.getContext("2d", { willReadFrequently: true });
cx.globalAlpha = 1;
for (const u of layerUnits()) {
if (u.obj.visible === false) continue;
const el = u.kind === "bitmap" ? u.obj.canvas : u.obj._canvas;
if (!el) continue;
cx.globalAlpha = u.kind === "bitmap" ? u.obj.opacity == null ? 1 : u.obj.opacity : 1;
cx.drawImage(el, 0, 0);
}
cx.globalAlpha = 1;
return c;
}
function getPickerComposite() {
if (!S.pickerComposite) {
S.pickerComposite = getCompositeCanvas().getContext("2d", { willReadFrequently: true });
}
return S.pickerComposite;
}
function sampleColor(pos) {
const x = clamp(Math.floor(pos.x), 0, Math.max(0, S.imgW - 1));
const y = clamp(Math.floor(pos.y), 0, Math.max(0, S.imgH - 1));
try {
const d = getPickerComposite().getImageData(x, y, 1, 1).data;
return { r: d[0], g: d[1], b: d[2], a: d[3] };
} catch (e) {
return null;
}
}
function showPickerTip(e, s) {
const tip = runtime.el.querySelector(".iwb-editor-picker-tip");
if (!tip) return;
const chip = tip.querySelector(".iwb-editor-picker-chip");
const hex = tip.querySelector(".iwb-editor-picker-hex");
if (s && s.a > 0) {
const h = rgbToHex(s.r, s.g, s.b);
chip.style.background = h;
chip.style.border = "1px solid rgba(255,255,255,0.3)";
hex.textContent = h;
} else {
chip.style.background = "transparent";
chip.style.border = "1px dashed rgba(255,255,255,0.4)";
hex.textContent = "透明";
}
tip.style.display = "flex";
tip.style.left = e.clientX + 16 + "px";
tip.style.top = e.clientY + 16 + "px";
}
function hidePickerTip() {
const tip = runtime.el.querySelector(".iwb-editor-picker-tip");
if (tip) tip.style.display = "none";
}
function exitPicker() {
if (S.altPicker) {
S.pickerComposite = null;
hidePickerTip();
return;
}
S.tool = S.prevTool && S.prevTool !== "picker" ? S.prevTool : "brush";
S.prevTool = null;
const back = S.tool;
if (back !== "select") {
S.selectedLayerId = null;
S.selectedTextId = null;
S.selectedShapeId = null;
}
S.pickerComposite = null;
hidePickerTip();
updateToolUI();
updateBrushParamUI();
if (S.tool === "crop") {
showCropBar();
updateCropInfo();
} else {
cancelCrop();
hideCropBar();
}
renderObjects();
}
function beginAltPicker() {
if (S.altPicker) return;
if (S.tool !== "brush" && S.tool !== "eraser") return;
if (S.isDrawing) return;
S.altPicker = true;
setTool("picker");
}
function endAltPicker() {
if (!S.altPicker) return;
S.altPicker = false;
exitPicker();
}
function applyColorChange(color, opts) {
const skipHistory = !!(opts && opts.skipHistory);
S.color = color;
if (!skipHistory) rememberColor(color);
updateColorUI();
const t = getSelectedText();
if (t && !t.locked && t.color !== S.color) {
if (!skipHistory) saveSnapshot();
t.color = S.color;
renderObjects();
}
const sh = getSelectedShape();
if (sh && !sh.locked && S.tool !== "text" && sh.color !== S.color) {
if (!skipHistory) saveSnapshot();
sh.color = S.color;
renderObjects();
}
}
function setTool(tool) {
if (S.placingImage) cancelImagePlacement();
commitTextInput();
if (tool !== "picker") S.altPicker = false;
if (tool !== "select") {
S.penEditId = null;
S.penDragPt = -1;
S.penDragPending = null;
}
if (tool === "picker" && S.tool !== "picker") S.prevTool = S.tool;
if (tool !== "pen") S.penPath = null;
if (tool === "crop") {
S.selection = null;
S.marquee = null;
S.lassoPts = null;
}
if (tool !== "marquee" && tool !== "lasso") {
if (S.marquee || S.lassoPts) {
S.isDrawing = false;
S.interaction = "idle";
}
S.marquee = null;
S.lassoPts = null;
}
S.tool = tool;
const keepSel = tool === "select" || tool === "picker";
if (!keepSel) {
S.selectedLayerId = null;
S.selectedTextId = null;
S.selectedShapeId = null;
}
S.bitmapDrag = null;
S.textDrag = null;
S.shapeDrag = null;
S.pickerComposite = null;
S.lastClick = null;
hidePickerTip();
updateToolUI();
updateBrushParamUI();
if (tool === "crop") {
showCropBar();
updateCropInfo();
} else {
cancelCrop();
hideCropBar();
}
renderObjects();
renderLayerPanel();
if (S.renderAll) S.renderAll();
}
// image-annotate/plugin/editor/commands.js
var COMMANDS = /* @__PURE__ */ Object.create(null);
function defineCommand(name, def) {
COMMANDS[name] = Object.assign({ label: name }, def || {});
}
function execute(label, mutator) {
const before = S.history.length;
saveSnapshot(label);
let result;
try {
result = mutator();
} catch (err) {
if (S.history.length === before + 1) S.history.pop();
throw err;
}
if (S.renderAll) S.renderAll();
return result;
}
function runCommand(name) {
const def = COMMANDS[name];
if (!def) return false;
if (S.tool === "crop" && String(name).indexOf("sel.") === 0) {
toast("裁剪中不可使用选区命令,请先切换工具", "warn");
return false;
}
if (typeof def.enabled === "function" && !def.enabled()) {
toast(def.hint || "当前状态下不可用", "warn");
return false;
}
const args = Array.prototype.slice.call(arguments, 1);
try {
if (def.view) {
const r = def.run.apply(null, args);
if (S.renderAll) S.renderAll();
return r;
}
return execute(def.label, () => def.run.apply(null, args));
} catch (err) {
console.error("[IWB编辑器] 命令执行失败:" + name, err);
toast("操作失败:" + (err && err.message || name), "error");
return false;
}
}
var toastTimer = null;
function toast(message, kind) {
const el = runtime.el && runtime.el.querySelector(".iwb-editor-toast");
if (!el) return;
el.textContent = String(message || "");
el.className = "iwb-editor-toast iwb-editor-toast-" + (kind || "info") + " show";
if (toastTimer) clearTimeout(toastTimer);
toastTimer = setTimeout(() => {
el.classList.remove("show");
toastTimer = null;
}, 2600);
}
// image-annotate/plugin/editor/text.js
var TEXT_LINE_HEIGHT = 1.25;
var BG_PAD_RATIO = 0.3;
var _measureCtx = null;
function measureCtx() {
if (!_measureCtx) {
const c = document.createElement("canvas");
c.width = 8;
c.height = 8;
_measureCtx = c.getContext("2d");
}
return _measureCtx;
}
function weightOf(t) {
const w = t && t.fontWeight;
return w == null || w === "" ? "bold" : String(w);
}
function fontOf(t) {
const size = Math.max(4, Number(t && t.fontSize) || 32);
return weightOf(t) + " " + size + "px sans-serif";
}
function textMetrics(t) {
const ctx = measureCtx();
const font = fontOf(t);
ctx.font = font;
const raw = (t && t.text) == null ? "" : String(t.text);
const lines = raw.split("\n");
const widths = lines.map((line) => ctx.measureText(line).width);
const size = Math.max(4, Number(t && t.fontSize) || 32);
const lh = size * (Number(t && t.lineHeight) || TEXT_LINE_HEIGHT);
const w = lines.length ? Math.max.apply(null, widths) : 0;
const pad = t && t.bgFill ? Math.round(size * BG_PAD_RATIO) : 0;
const sw = Math.max(0, Number(t && t.strokeWidth) || 0);
return { lines, widths, w, h: lh * lines.length, lh, pad, sw, font, size };
}
function textBox(t) {
const m = textMetrics(t);
const half = m.sw / 2;
return {
x: t.x - half,
y: t.y - half,
w: Math.max(m.w, 2) + m.pad * 2 + m.sw,
h: Math.max(m.h, 1) + m.pad * 2 + m.sw
};
}
function alignOf(t) {
const a = t && t.align;
return a === "center" || a === "right" ? a : "left";
}
function drawTextObject(ctx, t) {
const m = textMetrics(t);
ctx.save();
ctx.textBaseline = "top";
ctx.globalAlpha = t.opacity != null ? t.opacity : 1;
const b = textBox(t);
const rot = t.rotation || 0;
if (rot) {
const cx = b.x + b.w / 2;
const cy = b.y + b.h / 2;
ctx.translate(cx, cy);
ctx.rotate(rot * Math.PI / 180);
ctx.translate(-cx, -cy);
}
ctx.font = m.font;
const align = alignOf(t);
const boxW = m.w + m.pad * 2;
if (t.bgFill) {
const r = Math.min(m.pad + 2, Math.min(boxW, m.h + m.pad * 2) / 2);
ctx.globalAlpha = (t.opacity != null ? t.opacity : 1) * (t.bgAlpha == null ? 0.68 : t.bgAlpha);
ctx.fillStyle = t.bgColor || "#000000";
const bx = t.x, by = t.y;
const bw = boxW, bh = m.h + m.pad * 2;
ctx.beginPath();
if (typeof ctx.roundRect === "function") {
ctx.roundRect(bx, by, bw, bh, r);
} else {
ctx.moveTo(bx + r, by);
ctx.arcTo(bx + bw, by, bx + bw, by + bh, r);
ctx.arcTo(bx + bw, by + bh, bx, by + bh, r);
ctx.arcTo(bx, by + bh, bx, by, r);
ctx.arcTo(bx, by, bx + bw, by, r);
ctx.closePath();
}
ctx.fill();
ctx.globalAlpha = t.opacity != null ? t.opacity : 1;
}
ctx.textAlign = align;
const left = t.x + m.pad;
const ox = align === "center" ? left + m.w / 2 : align === "right" ? left + m.w : left;
ctx.lineJoin = "round";
ctx.miterLimit = 2;
for (let i = 0; i < m.lines.length; i++) {
const y = t.y + m.pad + i * m.lh;
if (m.sw > 0) {
ctx.lineWidth = m.sw;
ctx.strokeStyle = t.strokeColor || "#ffffff";
ctx.strokeText(m.lines[i], ox, y);
}
ctx.fillStyle = t.color || "#ff4444";
ctx.fillText(m.lines[i], ox, y);
}
ctx.restore();
}
function newTextStyle(src) {
const s = src || {};
return {
fontWeight: weightOf(s),
align: alignOf(s),
lineHeight: Number(s.lineHeight) || TEXT_LINE_HEIGHT,
strokeWidth: Math.max(0, Number(s.strokeWidth) || 0),
strokeColor: s.strokeColor || "#ffffff",
bgFill: !!s.bgFill,
bgColor: s.bgColor || "#000000",
bgAlpha: s.bgAlpha == null ? 0.68 : Number(s.bgAlpha)
};
}
// image-annotate/plugin/editor/snap.js
var SNAP_SCREEN_PX = 6;
var GUIDE_COLOR = "#ff2d95";
function pushBox(targets, box) {
const x2 = box.x + box.w;
const y2 = box.y + box.h;
targets.x.push(box.x, box.x + box.w / 2, x2);
targets.y.push(box.y, box.y + box.h / 2, y2);
}
function nearest(targets, sources, tol, axis) {
let best = null;
for (let i = 0; i < targets.length; i++) {
for (let j = 0; j < sources.length; j++) {
const delta = targets[i] - sources[j];
const abs = Math.abs(delta);
if (abs > tol) continue;
if (!best || abs < Math.abs(best.delta)) best = { delta, at: targets[i], axis };
}
}
return best;
}
function snapMove(box, others) {
const tol = SNAP_SCREEN_PX / Math.max(0.02, viewScale());
const targets = { x: [0, S.imgW / 2, S.imgW], y: [0, S.imgH / 2, S.imgH] };
for (const o of others || []) {
if (!o || !isFinite(o.x) || !isFinite(o.y)) continue;
pushBox(targets, o);
}
const sourcesX = [box.x, box.x + box.w / 2, box.x + box.w];
const sourcesY = [box.y, box.y + box.h / 2, box.y + box.h];
const gx = nearest(targets.x, sourcesX, tol, "x");
const gy = nearest(targets.y, sourcesY, tol, "y");
const guides = [];
if (gx) guides.push(gx);
if (gy) guides.push(gy);
return { dx: gx ? gx.delta : 0, dy: gy ? gy.delta : 0, guides };
}
function drawGuides(ctx, guides) {
if (!guides || !guides.length || !ctx) return;
const scale = viewScale();
const pad = S.overlayPad || 0;
ctx.save();
ctx.strokeStyle = GUIDE_COLOR;
ctx.lineWidth = 1 / Math.max(0.02, scale);
ctx.setLineDash([6 / Math.max(0.02, scale), 4 / Math.max(0.02, scale)]);
for (const g of guides) {
ctx.beginPath();
if (g.axis === "x") {
ctx.moveTo(g.at, -pad);
ctx.lineTo(g.at, S.imgH + pad);
} else {
ctx.moveTo(-pad, g.at);
ctx.lineTo(S.imgW + pad, g.at);
}
ctx.stroke();
}
ctx.setLineDash([]);
ctx.restore();
}
// image-annotate/plugin/editor/objects.js
function textBounds(t) {
return textBox(t);
}
function getSelectedText() {
return S.textLayers.find((t) => t.id === S.selectedTextId) || null;
}
function hitTextLayer(pos) {
for (let i = S.textLayers.length - 1; i >= 0; i--) {
const t = S.textLayers[i];
if (t.visible === false) continue;
const b = textBounds(t);
const rot = t.rotation || 0;
const lp = rot ? unrotPt(pos.x, pos.y, b.x + b.w / 2, b.y + b.h / 2, rot) : [pos.x, pos.y];
if (lp[0] >= b.x - 2 && lp[0] <= b.x + b.w + 2 && lp[1] >= b.y - 2 && lp[1] <= b.y + b.h + 2) {
return t;
}
}
return null;
}
function textHandlePoints(t) {
const b = textBounds(t);
const rot = t.rotation || 0;
const cx = b.x + b.w / 2, cy = b.y + b.h / 2;
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 out = {};
for (const k in local) out[k] = rotPt(local[k][0], local[k][1], cx, cy, rot);
return out;
}
function hitTextHandle(pos) {
const t = getSelectedText();
if (!t) return null;
const b = textBounds(t);
const rot = t.rotation || 0;
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 / viewScale();
let best = null, bestDist = 1e9;
for (const name in local) {
const dx = lp[0] - local[name][0], dy = lp[1] - local[name][1];
const d = dx * dx + dy * dy;
if (d < R * R && d < bestDist) {
bestDist = d;
best = name;
}
}
return best;
}
function shapeBounds(s) {
if (s.type === "pen" && s.pts && s.pts.length) {
const xs = s.pts.map((p) => p.x), ys = s.pts.map((p) => p.y), x = Math.min(...xs), y = Math.min(...ys);
return { x, y, w: Math.max(...xs) - x, h: Math.max(...ys) - y };
}
return { x: Math.min(s.x1, s.x2), y: Math.min(s.y1, s.y2), w: Math.abs(s.x2 - s.x1), h: Math.abs(s.y2 - s.y1) };
}
function getSelectedShape() {
return S.shapeLayers.find((s) => s.id === S.selectedShapeId) || null;
}
function distToSeg(px, py, x1, y1, x2, y2) {
const dx = x2 - x1, dy = y2 - y1;
const l2 = dx * dx + dy * dy;
let t = l2 ? ((px - x1) * dx + (py - y1) * dy) / l2 : 0;
t = clamp(t, 0, 1);
return Math.hypot(px - (x1 + t * dx), py - (y1 + t * dy));
}
function hitShapeObj(pos, s, includeInterior) {
if (s.visible === false) return false;
if (s.rotation) {
const b = shapeBounds(s);
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 / 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;
const rx = Math.max(0.5, b.w / 2), ry = Math.max(0.5, b.h / 2);
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 / 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;
}
if (s.type === "rect") {
const b = shapeBounds(s);
const pad = Math.max(4, s.lw * 1.5);
const inOuter = pos.x >= b.x - pad && pos.x <= b.x + b.w + pad && pos.y >= b.y - pad && pos.y <= b.y + b.h + pad;
if (!inOuter) return false;
if (includeInterior || s.fill) return true;
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 / viewScale(), s.lw);
}
function hitShapeLayer(pos, includeInterior) {
for (let i = S.shapeLayers.length - 1; i >= 0; i--) {
if (hitShapeObj(pos, S.shapeLayers[i], includeInterior)) return S.shapeLayers[i];
}
return null;
}
function allObjects() {
const arr = S.textLayers.map((o) => ({ kind: "text", obj: o })).concat(S.shapeLayers.map((o) => ({ kind: "shape", obj: o })));
arr.sort((a, b) => (a.obj.z || 0) - (b.obj.z || 0));
return arr;
}
function sortLayersByZ() {
const cmp = (a, b) => (a.z || 0) - (b.z || 0);
S.textLayers.sort(cmp);
S.shapeLayers.sort(cmp);
}
function layerUnits() {
const arr = S.layers.map((obj) => ({ kind: "bitmap", obj })).concat(S.textLayers.map((obj) => ({ kind: "text", obj }))).concat(S.shapeLayers.map((obj) => ({ kind: "shape", obj })));
arr.sort((a, b) => (a.obj.z || 0) - (b.obj.z || 0));
return arr;
}
function layerUnitsDesc() {
return layerUnits().reverse();
}
function assignLayerZ(units) {
units.forEach((u, i) => {
u.obj.z = i;
});
S.zCounter = Math.max(S.zCounter, units.length - 1);
}
function selectUnit(kind, id) {
S.layerMulti.length = 0;
S.selectedLayerId = kind === "bitmap" ? id : null;
S.selectedTextId = kind === "text" ? id : null;
S.selectedShapeId = kind === "shape" ? id : null;
S.textDrag = null;
S.shapeDrag = null;
S.bitmapDrag = null;
renderOptionBar();
}
function hitUnit(unit, pos) {
const { kind, obj } = unit;
if (!obj || obj.visible === false) return false;
if (kind === "bitmap") return obj.locked ? false : hitBitmapAt(obj, pos);
if (kind === "text") {
const b = textBounds(obj);
const rot = obj.rotation || 0;
const lp = rot ? unrotPt(pos.x, pos.y, b.x + b.w / 2, b.y + b.h / 2, rot) : [pos.x, pos.y];
return lp[0] >= b.x - 2 && lp[0] <= b.x + b.w + 2 && lp[1] >= b.y - 2 && lp[1] <= b.y + b.h + 2;
}
return hitShapeObj(pos, obj, true);
}
function hitTopmost(pos) {
for (const unit of layerUnitsDesc()) if (hitUnit(unit, pos)) return unit;
return null;
}
function otherObjectBoxes(exclude) {
const out = [];
for (const unit of layerUnits()) {
const o = unit.obj;
if (!o || o === exclude || o.id === "base" || o.visible === false) continue;
if (unit.kind === "bitmap") {
if (isFinite(o.x) && isFinite(o.y) && o.w > 0 && o.h > 0) out.push({ x: o.x, y: o.y, w: o.w, h: o.h });
} else if (unit.kind === "text") {
out.push(textBox(o));
} else {
out.push(shapeBounds(o));
}
}
return out;
}
function hitAnyObject(pos) {
for (const unit of layerUnitsDesc()) {
if (unit.kind === "bitmap") continue;
if (hitUnit(unit, pos)) return unit;
}
return null;
}
function getSelectedObject() {
const t = getSelectedText();
if (t) return { kind: "text", obj: t };
const s = getSelectedShape();
if (s) return { kind: "shape", obj: s };
return null;
}
function moveLayer(dir) {
let sel = getSelectedObject();
if (sel) {
if (sel.obj.locked) return;
} else {
const layer = S.layers.find((l) => l.id === S.selectedLayerId && l.id !== "base" && !l.locked);
if (layer) sel = { kind: "bitmap", obj: layer };
}
if (!sel) {
toast("先在画布或图层面板选中要调整的元素", "info");
return;
}
if (sel.obj.locked || sel.obj.id === "base") return;
const units = layerUnits();
const baseIdx = units.findIndex((u) => u.obj.id === "base");
if (baseIdx > 0) {
const [b] = units.splice(baseIdx, 1);
units.unshift(b);
}
const from = units.findIndex((u) => u.obj === sel.obj);
if (from < 0) return;
const min = baseIdx >= 0 ? 1 : 0;
let to;
if (dir === "up") to = Math.min(from + 1, units.length - 1);
else if (dir === "down") to = Math.max(from - 1, min);
else if (dir === "top") to = units.length - 1;
else if (dir === "bottom") to = min;
else return;
if (to === from) return;
saveSnapshot();
const [moved] = units.splice(from, 1);
units.splice(to, 0, moved);
assignLayerZ(units);
sortLayersByZ();
reorderLayerCanvas();
renderObjects();
renderLayerPanel();
}
function selectNeighborLayer(up) {
const units = layerUnits();
if (!units.length) return;
const sel = getSelectedObject();
let cur = -1;
if (sel) cur = units.findIndex((u2) => u2.obj === sel.obj);
else if (S.selectedLayerId) cur = units.findIndex((u2) => u2.kind === "bitmap" && u2.obj.id === S.selectedLayerId);
const idx = cur < 0 ? up ? units.length - 1 : 0 : up ? Math.min(cur + 1, units.length - 1) : Math.max(cur - 1, 0);
const u = units[idx];
if (!u) return;
selectUnit(u.kind, u.obj.id);
renderLayerPanel();
}
function shapeHandlePoints(s) {
const b = shapeBounds(s);
if (s.type === "pen") {
return Object.fromEntries((s.pts || []).map((p, i) => ["p" + i, [p.x, p.y]]));
}
if (s.type === "arrow") {
return { start: [s.x1, s.y1], end: [s.x2, s.y2] };
}
return {
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],
n: [b.x + b.w / 2, b.y],
s: [b.x + b.w / 2, b.y + b.h],
e: [b.x + b.w, b.y + b.h / 2],
w: [b.x, b.y + b.h / 2]
};
}
function shapeHandleWorld(s) {
const b = shapeBounds(s);
const rot = s.rotation || 0;
const cx = b.x + b.w / 2, cy = b.y + b.h / 2;
const local = shapeHandlePoints(s);
const out = {};
for (const k in local) out[k] = rotPt(local[k][0], local[k][1], cx, cy, rot);
return out;
}
function hitShapeHandle(pos) {
const s = getSelectedShape();
if (!s) return null;
const b = shapeBounds(s);
const rot = s.rotation || 0;
const cx = b.x + b.w / 2, cy = b.y + b.h / 2;
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 / 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);
const py = pts[name][1] + (name.includes("n") ? -offset : name.includes("s") ? offset : 0);
const dx = lp[0] - px, dy = lp[1] - py;
const d = dx * dx + dy * dy;
if (d < R * R && d < bestDist) {
bestDist = d;
best = name;
}
}
return best;
}
function applyShapeHandle(s, handle, pos) {
const b0 = shapeBounds(s);
const rot0 = s.rotation || 0;
const c0x = b0.x + b0.w / 2, c0y = b0.y + b0.h / 2;
if (handle === "rotate") {
const st = S.shapeDrag && S.shapeDrag.start;
const baseRot = S.shapeDrag && S.shapeDrag.shape && (S.shapeDrag.shape.rotation || 0) || 0;
if (st) {
const a0 = Math.atan2(st.y - c0y, st.x - c0x);
const a1 = Math.atan2(pos.y - c0y, pos.x - c0x);
let deg = baseRot + (a1 - a0) * 180 / Math.PI;
if (S._shiftDown) deg = Math.round(deg / 15) * 15;
s.rotation = deg;
}
return;
}
const lp = rot0 ? unrotPt(pos.x, pos.y, c0x, c0y, rot0) : [pos.x, pos.y];
pos = { x: lp[0], y: lp[1] };
if (s.type === "pen" && handle && handle[0] === "p") {
const i = parseInt(handle.slice(1), 10);
if (s.pts && s.pts[i]) {
s.pts[i].x = clamp(pos.x, 0, S.imgW);
s.pts[i].y = clamp(pos.y, 0, S.imgH);
}
return;
}
if (s.type === "arrow") {
if (handle === "start") {
s.x1 = clamp(pos.x, 0, S.imgW);
s.y1 = clamp(pos.y, 0, S.imgH);
} else {
s.x2 = clamp(pos.x, 0, S.imgW);
s.y2 = clamp(pos.y, 0, S.imgH);
}
return;
}
const b = shapeBounds(s);
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);
if (handle.includes("s")) y2 = Math.max(y1 + 2, adjusted.y);
if (handle.includes("w")) x1 = Math.min(x2 - 2, adjusted.x);
if (handle.includes("n")) y1 = Math.min(y2 - 2, adjusted.y);
s.x1 = x1;
s.y1 = y1;
s.x2 = x2;
s.y2 = y2;
}
function drawPenPathPreview() {
const path = S.penPath;
if (!path || !path.pts || !path.pts.length) return;
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 / 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);
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);
if (nearStart) {
ctx.closePath();
ctx.fill();
}
ctx.stroke();
ctx.setLineDash([]);
for (let i = 0; i < path.pts.length; i++) {
const point = path.pts[i];
ctx.beginPath();
ctx.fillStyle = i === 0 && nearStart ? "#e8a735" : "#ffffff";
ctx.strokeStyle = S.color;
ctx.arc(point.x, point.y, 6 / viewScale(), 0, Math.PI * 2);
ctx.fill();
ctx.stroke();
}
ctx.restore();
}
function drawShapeSelection(s) {
const octx = S.overlayCtx;
const b = shapeBounds(s);
const rot = s.rotation || 0;
octx.save();
octx.strokeStyle = "#e8a735";
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]);
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 / viewScale();
octx.fillStyle = "#ffffff";
octx.strokeStyle = "#e8a735";
const pts = shapeHandleWorld(s);
for (const name in pts) {
octx.beginPath();
octx.rect(pts[name][0] - hs, pts[name][1] - hs, hs * 2, hs * 2);
octx.fill();
octx.stroke();
}
octx.restore();
drawRotationHandles(octx, b, rot);
}
function deleteSelectedShape() {
if (!S.selectedShapeId) return;
const selected = getSelectedShape();
if (selected && selected.locked) return;
saveSnapshot();
removeVecCanvas(selected);
S.shapeLayers = S.shapeLayers.filter((s) => s.id !== S.selectedShapeId);
S.selectedShapeId = null;
renderObjects();
}
function renderObjects(tempShape) {
for (const { kind, obj } of allObjects()) drawVectorToCanvas(kind, obj);
reorderLayerCanvas();
clearOverlay();
drawGuides(S.overlayCtx, S.guides);
if (tempShape) drawShape(S.overlayCtx, tempShape);
if (S.tool === "pen" && S.penPath && S.penPath.pts.length) drawPenPathPreview();
if (S.placingImage) {
drawPlacementPreview();
return;
}
const bitmapSelection = S.layers.find((l) => l.id === S.selectedLayerId && (l.transformable || isDrawableLayer(l)));
if (bitmapSelection) drawBitmapSelection(bitmapSelection);
const sel = getSelectedText();
if (sel) {
const b = textBounds(sel);
const rot = sel.rotation || 0;
const octx = S.overlayCtx;
octx.save();
octx.strokeStyle = "#e8a735";
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 / viewScale();
octx.fillStyle = "#ffffff";
octx.strokeStyle = "#e8a735";
const pts = textHandlePoints(sel);
for (const name in pts) {
octx.beginPath();
octx.rect(pts[name][0] - hs, pts[name][1] - hs, hs * 2, hs * 2);
octx.fill();
octx.stroke();
}
octx.restore();
} else {
const sh = getSelectedShape();
if (sh) drawShapeSelection(sh);
}
const penShape = getPenEditingShape();
if (penShape) drawPenEditOverlay(penShape);
if (S.cropRect) drawCropPreview();
updateLayerUI();
}
function getPenEditingShape() {
if (!S.penEditId) return null;
return S.shapeLayers.find((sh) => sh.id === S.penEditId && sh.type === "pen") || null;
}
function beginPenEdit(shape) {
S.penEditId = shape.id;
S.selectedShapeId = shape.id;
S.selectedTextId = null;
S.selectedLayerId = null;
S.shapeDrag = null;
S.penDragPt = -1;
S.penDragBase = null;
S.penDragPending = null;
renderObjects();
renderLayerPanel();
}
function exitPenEdit() {
S.penEditId = null;
S.penDragPt = -1;
S.penDragBase = null;
S.penDragPending = null;
renderObjects();
renderLayerPanel();
}
function hitPenPoint(pos, shape, r) {
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];
for (let i = 0; i < pts.length; i++) {
if (Math.hypot(lp[0] - pts[i].x, lp[1] - pts[i].y) <= r) return i;
}
return -1;
}
function hitPenEdgeInsert(pos, shape) {
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 = 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;
}
if (shape.closed && pts.length >= 3) {
if (distToSeg(lp[0], lp[1], pts[pts.length - 1].x, pts[pts.length - 1].y, pts[0].x, pts[0].y) <= r) return pts.length - 1;
}
return -1;
}
function drawPenEditOverlay(shape) {
const ctx = S.overlayCtx;
const pts = shape.pts || [];
const b = shapeBounds(shape);
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 = 7 / viewScale();
ctx.save();
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]]);
ctx.strokeStyle = "#e8a735";
for (const [a, bb] of segments) {
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, 3 / viewScale(), 0, Math.PI * 2);
ctx.stroke();
}
for (let i = 0; i < pts.length; i++) {
const wp = W(pts[i]);
ctx.beginPath();
ctx.rect(wp[0] - R / 2, wp[1] - R / 2, R, R);
ctx.fillStyle = "#ffffff";
ctx.strokeStyle = i === S.penDragPt ? "#ff8c00" : "#e8a735";
ctx.fill();
ctx.stroke();
}
ctx.restore();
}
function showTextInput(x, y, layer) {
const input = runtime.el.querySelector(".iwb-editor-text-input");
const wrapRect = S.canvasWrap.getBoundingClientRect();
const box = (S.textCanvas || S.canvasStack).getBoundingClientRect();
const sx = S.imgW ? box.width / S.imgW : 1;
const sy = S.imgH ? box.height / S.imgH : 1;
const INSET_X = 10;
const INSET_Y = 6;
input.style.left = box.left - wrapRect.left + x * sx - INSET_X + "px";
input.style.top = box.top - wrapRect.top + y * sy - INSET_Y + "px";
input.style.display = "block";
if (layer) {
input.value = layer.text;
S.textEditingId = layer.id;
} else {
input.value = "";
S.textEditingId = null;
}
input.focus();
input.select();
input.dataset.x = x;
input.dataset.y = y;
input.style.height = "auto";
input.style.height = Math.max(30, input.scrollHeight + 4) + "px";
}
function hideTextInput() {
const input = runtime.el.querySelector(".iwb-editor-text-input");
if (input) {
if (document.activeElement === input) input.blur();
input.style.display = "none";
input.value = "";
}
S.textEditingId = null;
}
function commitTextInput() {
const input = runtime.el.querySelector(".iwb-editor-text-input");
if (!input || input.style.display === "none") return false;
const text = input.value.trim();
const x = parseFloat(input.dataset.x);
const y = parseFloat(input.dataset.y);
let committed = false;
if (S.textEditingId) {
const t = S.textLayers.find((l) => l.id === S.textEditingId);
if (t && t.locked) {
hideTextInput();
return true;
}
if (t && text !== t.text) {
saveSnapshot();
if (text) {
t.text = text;
} else {
removeVecCanvas(t);
S.textLayers = S.textLayers.filter((l) => l.id !== t.id);
S.selectedTextId = null;
}
renderObjects();
}
committed = true;
} else if (text) {
saveSnapshot();
const layer = {
id: "t" + Date.now() + Math.floor(Math.random() * 1e3),
x,
y,
text,
color: S.color,
fontSize: Math.max(8, S.textSize),
// 样式一次性随默认值落进对象:老对象没有这些字段,text.js 会各自回退到等价默认值
...newTextStyle({
fontWeight: S.textWeight,
align: S.textAlign,
lineHeight: S.textLineHeight,
strokeWidth: S.textStrokeWidth,
strokeColor: S.textStrokeColor,
bgFill: S.textBgFill,
bgColor: S.textBgColor
}),
opacity: 1,
visible: true,
locked: false,
z: ++S.zCounter
};
S.textLayers.push(layer);
selectUnit("text", layer.id);
renderObjects();
committed = true;
}
hideTextInput();
if (committed) {
const id = S.selectedTextId;
queueMicrotask(() => {
if (S.tool !== "text") return;
const box = runtime.el && runtime.el.querySelector(".iwb-editor-text-input");
if (box && box.style.display !== "none") return;
setTool("select");
if (!id) return;
selectUnit("text", id);
renderObjects();
renderLayerPanel();
});
}
return committed;
}
function deleteSelectedText() {
if (!S.selectedTextId) return;
const selected = getSelectedText();
if (selected && selected.locked) return;
saveSnapshot();
removeVecCanvas(selected);
S.textLayers = S.textLayers.filter((t) => t.id !== S.selectedTextId);
S.selectedTextId = null;
renderObjects();
}
function beginTextRotate(pos) {
const t = getSelectedText();
if (!t || t.locked) return;
const b = textBounds(t);
S.textDrag = {
mode: "rotate",
rotation: t.rotation || 0,
cx: b.x + b.w / 2,
cy: b.y + b.h / 2,
startX0: pos.x,
startY0: pos.y,
pending: snapshotState()
};
}
function beginTextScaleDrag(handle, pos) {
const t = getSelectedText();
if (!t || t.locked) return;
const b = textBounds(t);
const rot = t.rotation || 0;
const cx = b.x + b.w / 2, cy = b.y + b.h / 2;
const anchors = {
se: [b.x, b.y],
ne: [b.x, b.y + b.h],
sw: [b.x + b.w, b.y],
nw: [b.x + b.w, b.y + b.h]
};
const a = rotPt(anchors[handle][0], anchors[handle][1], cx, cy, rot);
const anchor = { x: a[0], y: a[1] };
const dx = pos.x - anchor.x, dy = pos.y - anchor.y;
S.textDrag = {
mode: "scale",
anchor,
d0: Math.sqrt(dx * dx + dy * dy),
fontSize: t.fontSize,
pending: snapshotState()
};
}
function beginShapeHandleDrag(handle, pos) {
const sh = getSelectedShape();
if (!sh || sh.locked) return;
S.shapeDrag = {
mode: "handle",
handle,
start: pos,
shape: { ...sh },
pending: snapshotState()
};
}
// image-annotate/plugin/editor/layers.js
function createLayerCanvas() {
const c = document.createElement("canvas");
c.className = "iwb-editor-layer-canvas";
c.width = S.imgW;
c.height = S.imgH;
c.style.position = "absolute";
c.style.top = "0";
c.style.left = "0";
c.style.display = "block";
S.canvasStack.insertBefore(c, S.strokeCanvas);
return c;
}
function reorderLayerCanvas() {
for (const u of layerUnits()) {
const el = u.kind === "bitmap" ? u.obj.canvas : u.obj._canvas;
if (!el || el.nodeType !== 1) continue;
S.canvasStack.insertBefore(el, S.strokeCanvas);
el.style.display = u.obj.visible === false ? "none" : "block";
}
}
function getActiveLayer() {
return S.layers.find((l) => l.id === S.activeLayerId) || null;
}
function getActiveCtx() {
const layer = getActiveLayer();
return layer && !layer.locked ? layer.ctx : null;
}
function clearSelection({ keepBitmap = false } = {}) {
if (!keepBitmap) S.selectedLayerId = null;
S.selectedTextId = null;
S.selectedShapeId = null;
S.textDrag = null;
S.shapeDrag = null;
S.bitmapDrag = null;
}
function resolveSourceBox(layer) {
if (layer._srcBox && layer.sourceCanvas) {
const b = layer._srcBox;
return { src: layer.sourceCanvas, box: b };
}
if (layer.image && layer.w > 0 && layer.h > 0) return { src: layer.image, box: null };
if (layer.sourceCanvas && layer.w > 0 && layer.h > 0) return { src: layer.sourceCanvas, box: null };
return null;
}
function paintTransformed(layer, source) {
const rot = layer.rotation || 0;
const cx = layer.x + layer.w / 2, cy = layer.y + layer.h / 2;
layer.ctx.save();
if (rot) {
layer.ctx.translate(cx, cy);
layer.ctx.rotate(rot * Math.PI / 180);
layer.ctx.translate(-cx, -cy);
}
if (source) {
if (source.box) {
const b = source.box;
layer.ctx.drawImage(source.src, b.x, b.y, b.w, b.h, layer.x, layer.y, layer.w, layer.h);
} else {
layer.ctx.drawImage(source.src, layer.x, layer.y, layer.w, layer.h);
}
}
layer.ctx.restore();
}
function redrawBitmapLayer(layer) {
if (!layer || !layer.ctx) return;
layer.ctx.clearRect(0, 0, S.imgW, S.imgH);
paintTransformed(layer, resolveSourceBox(layer));
}
function hitBitmapHandle(pos) {
const layer = S.layers.find((l) => l.id === S.selectedLayerId && (l.transformable || isDrawableLayer(l)));
if (!layer || layer.visible === false) return null;
const box = layerFrame(layer);
if (!(box.w > 0 && box.h > 0)) return null;
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 / viewScale();
if (hitRotationHandle(lp, box)) return "rotate";
const points = {
nw: [box.x, box.y],
ne: [box.x + box.w, box.y],
sw: [box.x, box.y + box.h],
se: [box.x + box.w, box.y + box.h],
n: [box.x + box.w / 2, box.y],
s: [box.x + box.w / 2, box.y + box.h],
e: [box.x + box.w, box.y + box.h / 2],
w: [box.x, box.y + box.h / 2]
};
let hit = null, best = Infinity;
for (const name in points) {
const distance = Math.hypot(lp[0] - points[name][0], lp[1] - points[name][1]);
if (distance < R && distance < best) {
best = distance;
hit = name;
}
}
return hit;
}
function layerBounds(layer) {
if (!layer || !layer.ctx || !layer.canvas) return null;
if (layer._bounds !== void 0) return layer._bounds;
let b = null;
try {
const w = layer.canvas.width, h = layer.canvas.height;
const data = layer.ctx.getImageData(0, 0, w, h).data;
let minX = w, minY = h, maxX = -1, maxY = -1;
for (let y = 0; y < h; y += 2) {
for (let x = 0; x < w; x += 2) {
if (data[(y * w + x) * 4 + 3] > 8) {
if (x < minX) minX = x;
if (x > maxX) maxX = x;
if (y < minY) minY = y;
if (y > maxY) maxY = y;
}
}
}
if (maxX >= 0) b = { x: minX, y: minY, w: maxX - minX + 2, h: maxY - minY + 2 };
} catch (e) {
b = null;
}
layer._bounds = b;
return b;
}
function layerFrame(layer) {
if (isDrawableLayer(layer) && !layer._srcBox) {
const b = layerBounds(layer);
if (b) return b;
}
return { x: layer.x, y: layer.y, w: layer.w, h: layer.h };
}
function hitBitmapAt(layer, pos) {
if (!layer || layer.visible === false || layer.locked) return false;
const drawable = isDrawableLayer(layer);
if (!drawable && !layer.transformable) return false;
if (!(layer.w > 0 && layer.h > 0)) return false;
const rot = layer.rotation || 0;
const lp = rot ? unrotPt(pos.x, pos.y, layer.x + layer.w / 2, layer.y + layer.h / 2, rot) : [pos.x, pos.y];
if (lp[0] < layer.x || lp[0] > layer.x + layer.w || lp[1] < layer.y || lp[1] > layer.y + layer.h) return false;
if (!drawable) return true;
const px = Math.round(lp[0]), py = Math.round(lp[1]);
if (px < 0 || py < 0 || px >= layer.canvas.width || py >= layer.canvas.height) return false;
try {
return layer.ctx.getImageData(px, py, 1, 1).data[3] > 8;
} catch (e) {
return true;
}
}
function drawBitmapSelection(layer) {
if (!layer) return;
if (S.tool !== "select") return;
const drawable = isDrawableLayer(layer);
if (!layer.transformable && !drawable) return;
const box = layerFrame(layer);
if (!(box.w > 0 && box.h > 0)) return;
const ctx = S.overlayCtx;
const rot = layer.rotation || 0;
const hs = 5.5 / viewScale();
ctx.save();
ctx.strokeStyle = "#e8a735";
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]);
for (let i = 1; i < corners.length; i++) ctx.lineTo(corners[i][0], corners[i][1]);
ctx.closePath();
ctx.stroke();
ctx.setLineDash([]);
ctx.fillStyle = "#fff";
ctx.strokeStyle = "#e8a735";
const pts = frameHandlePoints(box, rot);
for (const name in pts) {
ctx.beginPath();
ctx.rect(pts[name][0] - hs, pts[name][1] - hs, hs * 2, hs * 2);
ctx.fill();
ctx.stroke();
}
ctx.restore();
drawRotationHandles(ctx, box, rot);
}
function frameHandlePoints(box, rot) {
const cx = box.x + box.w / 2, cy = box.y + box.h / 2;
const local = {
nw: [box.x, box.y],
ne: [box.x + box.w, box.y],
sw: [box.x, box.y + box.h],
se: [box.x + box.w, box.y + box.h],
n: [box.x + box.w / 2, box.y],
s: [box.x + box.w / 2, box.y + box.h],
e: [box.x + box.w, box.y + box.h / 2],
w: [box.x, box.y + box.h / 2]
};
const out = {};
for (const k in local) out[k] = rotPt(local[k][0], local[k][1], cx, cy, rot || 0);
return out;
}
function beginBitmapDrag(handle, pos) {
const layer = S.layers.find((l) => l.id === S.selectedLayerId);
if (!layer || layer.locked) return;
const drawable = isDrawableLayer(layer);
if (!layer.transformable && !drawable) return;
if (drawable) {
if (!layer.sourceCanvas) {
const sc = document.createElement("canvas");
sc.width = S.imgW;
sc.height = S.imgH;
sc.getContext("2d").drawImage(layer.canvas, 0, 0);
layer.sourceCanvas = sc;
}
if (!layer._srcBox) {
const b = layerBounds(layer) || { x: layer.x, y: layer.y, w: layer.w, h: layer.h };
layer._srcBox = { x: b.x, y: b.y, w: b.w, h: b.h };
layer.x = b.x;
layer.y = b.y;
layer.w = b.w;
layer.h = b.h;
layer.rotation = layer.rotation || 0;
}
}
const frame = layerFrame(layer);
S.bitmapDrag = {
mode: handle === "rotate" ? "rotate" : handle ? "scale" : "move",
handle,
start: pos,
drawable: isDrawableLayer(layer),
layer: { x: layer.x, y: layer.y, w: layer.w, h: layer.h, rotation: layer.rotation || 0 },
frame: { x: frame.x, y: frame.y, w: frame.w, h: frame.h },
pending: snapshotState()
};
}
function applyBitmapDrag(pos) {
const drag = S.bitmapDrag;
const layer = S.layers.find((l) => l.id === S.selectedLayerId);
if (!drag || !layer) return;
const base = drag.layer;
if (drag.mode === "move") {
let nx = base.x + pos.x - drag.start.x;
let ny = base.y + pos.y - drag.start.y;
if (!S._altDown && base.w > 0 && base.h > 0) {
const s = snapMove({ x: nx, y: ny, w: base.w, h: base.h }, otherObjectBoxes(layer));
nx += s.dx;
ny += s.dy;
S.guides = s.guides.length ? s.guides : null;
} else {
S.guides = null;
}
layer.x = nx;
layer.y = ny;
if (isDrawableLayer(layer)) layer._bounds = void 0;
} else if (drag.mode === "rotate") {
const rcx = base.x + base.w / 2, rcy = base.y + base.h / 2;
const a0 = Math.atan2(drag.start.y - rcy, drag.start.x - rcx);
const a1 = Math.atan2(pos.y - rcy, pos.x - rcx);
let deg = (base.rotation || 0) + (a1 - a0) * 180 / Math.PI;
if (S._shiftDown) deg = Math.round(deg / 15) * 15;
layer.rotation = deg;
} else {
const lpos = unrotPt(pos.x, pos.y, base.x + base.w / 2, base.y + base.h / 2, base.rotation || 0);
let x = base.x, y = base.y, w = base.w, h = base.h;
const min = 4;
if (drag.handle.includes("e")) w = Math.max(min, lpos[0] - base.x);
if (drag.handle.includes("s")) h = Math.max(min, lpos[1] - base.y);
if (drag.handle.includes("w")) {
x = Math.min(lpos[0], base.x + base.w - min);
w = base.x + base.w - x;
}
if (drag.handle.includes("n")) {
y = Math.min(lpos[1], base.y + base.h - min);
h = base.y + base.h - y;
}
if (S._shiftDown && layer.image) {
const iw = layer.image.naturalWidth || layer.image.width;
const ih = layer.image.naturalHeight || layer.image.height;
const aspect = iw / Math.max(1, ih);
if (w / h > aspect) h = w / aspect;
else w = h * aspect;
if (drag.handle.includes("w")) x = base.x + base.w - w;
if (drag.handle.includes("n")) y = base.y + base.h - h;
}
layer.x = x;
layer.y = y;
layer.w = w;
layer.h = h;
}
if (isDrawableLayer(layer)) layer._bounds = void 0;
redrawBitmapLayer(layer);
}
function setActiveLayer(id) {
const changed = S.activeLayerId !== id || S.selectedLayerId !== id;
S.activeLayerId = id;
selectUnit("bitmap", id);
if (!changed) return;
renderLayerPanel();
renderObjects();
if (S.renderFxPanel) S.renderFxPanel();
}
function addBitmapLayer(img) {
placeImageDirectly(img);
}
function ensureWritableLayer() {
const current = getActiveLayer();
if (current && !current.locked) return current;
const id = S.layers.some((l) => l.id === "draw") ? "L" + Date.now() + Math.floor(Math.random() * 1e3) : "draw";
const canvas = createLayerCanvas();
const ctx = canvas.getContext("2d", { willReadFrequently: true });
ctx.clearRect(0, 0, S.imgW, S.imgH);
const layer = {
id,
name: "标注 " + (S.layers.filter((l) => l.id !== "base").length + 1),
canvas,
ctx,
opacity: 1,
visible: true,
locked: false,
x: 0,
y: 0,
w: S.imgW,
h: S.imgH,
rotation: 0,
z: ++S.zCounter
};
S.layers.push(layer);
reorderLayerCanvas();
updateLayerCanvasStyles();
setActiveLayer(id);
renderLayerPanel();
return layer;
}
function addBlankLayer() {
const id = "L" + Date.now() + Math.floor(Math.random() * 1e3);
const canvas = createLayerCanvas();
const ctx = canvas.getContext("2d", { willReadFrequently: true });
ctx.clearRect(0, 0, S.imgW, S.imgH);
const layer = {
id,
name: "空白图层 " + (S.layers.length + 1),
canvas,
ctx,
opacity: 1,
visible: true,
locked: false,
x: 0,
y: 0,
w: S.imgW,
h: S.imgH,
rotation: 0,
z: ++S.zCounter
};
saveSnapshot();
S.layers.push(layer);
reorderLayerCanvas();
setActiveLayer(id);
updateLayerCanvasStyles();
renderLayerPanel();
}
function deleteLayer(id) {
const idx = S.layers.findIndex((l) => l.id === id);
if (idx < 0) return;
if (S.layers.length <= 1) return;
const layer = S.layers[idx];
if (layer.locked) return;
saveSnapshot();
if (layer.canvas.parentNode) layer.canvas.parentNode.removeChild(layer.canvas);
S.layers.splice(idx, 1);
assignLayerZ(layerUnits());
if (S.activeLayerId === id) S.activeLayerId = S.layers[S.layers.length - 1].id;
if (S.selectedLayerId === id) S.selectedLayerId = null;
reorderLayerCanvas();
renderLayerPanel();
}
function vecCanvasFor(obj) {
if (!obj._canvas || obj._canvas.nodeType !== 1 || !obj._canvas.parentNode) {
const c = document.createElement("canvas");
c.className = "iwb-editor-vec-canvas";
c.width = S.imgW;
c.height = S.imgH;
c.style.position = "absolute";
c.style.top = "0";
c.style.left = "0";
c.style.display = "block";
S.canvasStack.insertBefore(c, S.strokeCanvas);
if (S.imgW && S.fitW) {
const vw = Math.round(S.fitW * S.zoom);
const vh = Math.round(S.fitH * S.zoom);
const vs = S.imgW ? S.fitW * S.zoom / S.imgW : 1;
const vo = Math.round((S.overlayPad || 0) * vs);
c.style.width = vw + "px";
c.style.height = vh + "px";
c.style.left = vo + "px";
c.style.top = vo + "px";
}
obj._canvas = c;
obj._ctx = c.getContext("2d");
}
return obj;
}
function removeVecCanvas(obj) {
if (obj && obj._canvas && obj._canvas.nodeType === 1) {
if (obj._canvas.parentNode) obj._canvas.parentNode.removeChild(obj._canvas);
obj._canvas = null;
obj._ctx = null;
}
}
function purgeVectorCanvases() {
for (const t of S.textLayers) removeVecCanvas(t);
for (const sh of S.shapeLayers) removeVecCanvas(sh);
}
function drawVectorToCanvas(kind, obj) {
vecCanvasFor(obj);
const ctx = obj._ctx;
ctx.clearRect(0, 0, S.imgW, S.imgH);
if (kind === "shape") {
drawShape(ctx, obj);
} else {
drawTextObject(ctx, obj);
}
}
function toggleLayerVisibility(id) {
const layer = S.layers.find((l) => l.id === id);
if (!layer) return;
layer.visible = !layer.visible;
reorderLayerCanvas();
renderLayerPanel();
S.pickerComposite = null;
}
function updateLayerCanvasStyles() {
const w = Math.round(S.fitW * S.zoom);
const h = Math.round(S.fitH * S.zoom);
const scale = S.imgW ? S.fitW * S.zoom / S.imgW : 1;
const offset = Math.round((S.overlayPad || 0) * scale);
for (const layer of S.layers) {
layer.canvas.style.width = w + "px";
layer.canvas.style.height = h + "px";
layer.canvas.style.left = offset + "px";
layer.canvas.style.top = offset + "px";
layer.canvas.style.opacity = String(layer.opacity == null ? 1 : layer.opacity);
}
styleVectorViewport(w, h, offset);
}
function styleVectorViewport(w, h, offset) {
for (const { obj } of allObjects()) {
if (!obj._canvas) continue;
obj._canvas.style.width = w + "px";
obj._canvas.style.height = h + "px";
obj._canvas.style.left = offset + "px";
obj._canvas.style.top = offset + "px";
}
}
function esc(v) {
return String(v == null ? "" : v).replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;");
}
function opacityPct(v) {
const n = v == null ? 1 : v;
return Math.max(0, Math.min(100, Math.round(n * 100)));
}
function findPanelTarget(type, id) {
if (type === "bitmap") return S.layers.find((l) => l.id === id) || null;
if (type === "text") return S.textLayers.find((t) => t.id === id) || null;
if (type === "shape") return S.shapeLayers.find((s) => s.id === id) || null;
return null;
}
function applyOpacityVisual(type, obj) {
if (type === "bitmap" && obj && obj.canvas) {
obj.canvas.style.opacity = String(obj.opacity == null ? 1 : obj.opacity);
return;
}
if (type === "text" || type === "shape") renderObjects();
}
function renderLayerPanel() {
const list = runtime.el.querySelector(".iwb-editor-layer-list");
if (!list) return;
if (S.layerMulti.length) {
const alive = new Set(layerUnits().map((u) => u.kind + ":" + u.obj.id));
S.layerMulti = S.layerMulti.filter((r) => alive.has(r.type + ":" + r.id));
}
const items = [];
const multiSet = new Set(S.layerMulti.map((x) => x.type + ":" + x.id));
for (const { kind, obj } of layerUnitsDesc()) {
if (kind === "bitmap") {
items.push({
id: obj.id,
type: "bitmap",
name: obj.name,
opacity: obj.opacity,
visible: obj.visible,
z: obj.z,
color: obj.color || S.color,
lineWidth: obj.lineWidth || S.brushSize,
// 高亮只代表「选中」;画笔作用目标独立用 ✎ 标记,避免两个图层同时亮
active: obj.id === S.selectedLayerId,
multi: multiSet.has("bitmap:" + obj.id),
paintTarget: obj.id === S.activeLayerId,
locked: !!obj.locked,
canDelete: S.layers.length > 1
});
} else {
items.push({
id: obj.id,
type: kind,
name: kind === "text" ? '"' + (obj.text || "").slice(0, 12) + '"' : obj.type === "rect" ? "矩形" : obj.type === "circle" ? "圆形" : obj.type === "pen" ? "钢笔形状" : "箭头",
opacity: obj.opacity != null ? obj.opacity : 1,
visible: obj.visible !== false,
z: obj.z || 0,
color: obj.color || S.color,
lineWidth: obj.lw || S.brushSize,
active: kind === "text" && obj.id === S.selectedTextId || kind === "shape" && obj.id === S.selectedShapeId,
multi: multiSet.has(kind + ":" + obj.id),
paintTarget: false,
locked: !!obj.locked,
canDelete: true
});
}
}
let html = "";
for (const item of items) {
const activeClass = item.active ? " active" : "";
const multiClass = item.multi ? " multi" : "";
const visClass = item.visible ? "" : " hidden";
let typeIconSvg = "";
if (item.type === "bitmap") {
typeIconSvg = '<svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><rect x="3" y="3" width="18" height="18" rx="2"/><circle cx="8.5" cy="8.5" r="1.5"/><polyline points="21 15 16 10 5 21"/></svg>';
} else if (item.type === "text") {
typeIconSvg = '<svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><polyline points="4 7 4 3 20 3 20 7"/><line x1="9" y1="20" x2="15" y2="20"/><line x1="12" y1="3" x2="12" y2="20"/></svg>';
} else if (item.type === "rect") {
typeIconSvg = '<svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><rect x="3" y="3" width="18" height="18" rx="2"/></svg>';
} else {
typeIconSvg = '<svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><line x1="5" y1="12" x2="19" y2="12"/><polyline points="12 5 19 12 12 19"/></svg>';
}
const visSvg = item.visible ? '<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M2 12s3-7 10-7 10 7 10 7-3 7-10 7-10-7-10-7Z"/><circle cx="12" cy="12" r="3"/></svg>' : '<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M9.88 9.88a3 3 0 1 0 4.24 4.24"/><path d="M10.73 5.08A10.43 10.43 0 0 1 12 5c7 0 10 7 10 7a13.16 13.16 0 0 1-1.67 2.68"/><path d="M6.61 6.61A13.526 13.526 0 0 0 2 12s3 7 10 7a9.74 9.74 0 0 0 5.39-1.61"/><line x1="2" y1="2" x2="22" y2="22"/></svg>';
const lockSvg = item.locked ? '<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><rect x="5" y="10" width="14" height="10" rx="2"/><path d="M8 10V7a4 4 0 0 1 8 0v3"/></svg>' : '<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><rect x="5" y="10" width="14" height="10" rx="2"/><path d="M8 10V7a4 4 0 0 1 7-2"/></svg>';
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";
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" 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>` : ""}
<button class="iwb-layer-lock${item.locked ? " active" : ""}" data-lock-id="${item.id}" data-lock-type="${item.type}" title="${item.locked ? "解锁图层" : "锁定图层"}">${lockSvg}</button>
${item.canDelete ? `<button class="iwb-layer-del" data-del-id="${item.id}" data-del-type="${item.type}" title="删除图层">${delSvg}</button>` : ""}
</div>
${item.active ? `<div class="iwb-layer-op-row">
<input class="iwb-layer-opacity" type="range" min="0" max="100" step="1" value="${pct}" data-op-id="${item.id}" data-op-type="${item.type}" title="不透明度:拖动调整,双击复位 100%">
<span class="iwb-layer-op-val">${pct}%</span>
</div>` : ""}
</div>`;
}
list.innerHTML = html;
scheduleThumbs();
const fxTarget = runtime.el.querySelector(".iwb-editor-fx-target");
if (fxTarget) {
const active = getActiveLayer();
fxTarget.textContent = active ? active.name : "无图层";
fxTarget.title = active ? "效果作用于当前位图图层:" + active.name + "(切换图层可改变目标)" : "当前没有可处理的位图图层";
}
bindLayerPanelEvents();
}
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);
}
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);
bindLayerLockButtons(list);
bindLayerDelButtons(list);
}
function bindLayerItemEvents(list) {
list.querySelectorAll(".iwb-layer-item").forEach((item) => {
item.addEventListener("mousedown", (e) => e.stopPropagation());
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;
const id = item.dataset.layerId;
const type = item.dataset.layerType;
if (e.metaKey || e.ctrlKey) {
e.preventDefault();
toggleLayerMulti(type, id);
renderLayerPanel();
return;
}
if (S.layerMulti.length) S.layerMulti.length = 0;
if (type === "bitmap") {
setActiveLayer(id);
} else if (type === "text" || type === "shape") {
selectUnit(type, id);
renderObjects();
renderLayerPanel();
}
});
});
}
function bindLayerNameRename(list) {
list.querySelectorAll(".iwb-layer-name.renamable").forEach((el) => {
el.addEventListener("mousedown", (e) => {
e.stopPropagation();
const id = el.dataset.nameId;
const now = Date.now();
const prev = S.lastNameClick;
if (prev && prev.id === id && now - prev.t < 400) {
S.lastNameClick = null;
beginRename(id);
return;
}
S.lastNameClick = { id, t: now };
});
});
}
function beginRename(id) {
const list = runtime.el.querySelector(".iwb-editor-layer-list");
const layer = S.layers.find((l) => l.id === id);
if (!list || !layer) return;
const item = list.querySelector('.iwb-layer-item[data-layer-id="' + id + '"]');
const span = item && item.querySelector(".iwb-layer-name");
if (!span || !span.parentNode) return;
const input = document.createElement("input");
input.className = "iwb-layer-name-input";
input.type = "text";
input.value = layer.name;
input.maxLength = 40;
span.replaceWith(input);
let done = false;
const finish = (commit) => {
if (done) return;
done = true;
const next = input.value.trim();
if (commit && next && next !== layer.name) {
saveSnapshot("重命名图层");
layer.name = next;
}
renderLayerPanel();
};
input.addEventListener("mousedown", (e) => e.stopPropagation());
input.addEventListener("click", (e) => e.stopPropagation());
input.addEventListener("keydown", (e) => {
e.stopPropagation();
if (e.key === "Enter") {
e.preventDefault();
finish(true);
} else if (e.key === "Escape") {
e.preventDefault();
finish(false);
}
});
input.addEventListener("blur", () => finish(true));
input.focus();
input.select();
}
function bindLayerOpacityInputs(list) {
list.querySelectorAll(".iwb-layer-opacity").forEach((input) => {
input.addEventListener("mousedown", (e) => e.stopPropagation());
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) {
const type = input.dataset.opType;
const obj = findPanelTarget(type, input.dataset.opId);
if (!obj) return;
const pct = clamp(parseInt(input.value, 10) || 0, 0, 100);
if (!input._opSnapTaken) {
input._opSnapTaken = true;
saveSnapshot("调整不透明度");
}
obj.opacity = pct / 100;
applyOpacityVisual(type, obj);
S.pickerComposite = null;
const val = input.parentNode && input.parentNode.querySelector(".iwb-layer-op-val");
if (val) val.textContent = pct + "%";
}
var _thumbTimer = 0;
function scheduleThumbs() {
if (_thumbTimer) return;
_thumbTimer = setTimeout(() => {
_thumbTimer = 0;
paintThumbs();
}, 90);
}
function paintThumbs() {
if (!runtime.el) return;
const list = runtime.el.querySelector(".iwb-editor-layer-list");
if (!list) return;
list.querySelectorAll(".iwb-layer-thumb canvas").forEach((cv) => {
const type = cv.dataset.thumbType;
const obj = findPanelTarget(type, cv.dataset.thumbId);
const src = obj ? type === "bitmap" ? obj.canvas : obj._canvas : null;
const g = cv.getContext("2d");
if (!g) return;
g.clearRect(0, 0, cv.width, cv.height);
if (!src || !src.width || !src.height) return;
const k = Math.min(cv.width / src.width, cv.height / src.height);
const dw = Math.max(1, Math.round(src.width * k));
const dh = Math.max(1, Math.round(src.height * k));
try {
g.imageSmoothingQuality = "high";
g.drawImage(src, Math.round((cv.width - dw) / 2), Math.round((cv.height - dh) / 2), dw, dh);
} catch (e) {
}
});
}
function bindLayerVisButtons(list) {
list.querySelectorAll(".iwb-layer-vis").forEach((btn) => {
btn.addEventListener("mousedown", (e) => e.stopPropagation());
btn.addEventListener("click", (e) => {
e.stopPropagation();
const id = btn.dataset.visId;
const type = btn.dataset.visType;
if (type === "bitmap") {
toggleLayerVisibility(id);
} else if (type === "text") {
const obj = S.textLayers.find((t) => t.id === id);
if (obj) {
obj.visible = obj.visible === false;
renderObjects();
renderLayerPanel();
S.pickerComposite = null;
}
} else if (type === "shape") {
const obj = S.shapeLayers.find((s) => s.id === id);
if (obj) {
obj.visible = obj.visible === false;
renderObjects();
renderLayerPanel();
S.pickerComposite = null;
}
}
});
});
}
function bindLayerLockButtons(list) {
list.querySelectorAll(".iwb-layer-lock").forEach((btn) => {
btn.addEventListener("mousedown", (e) => e.stopPropagation());
btn.addEventListener("click", (e) => {
e.stopPropagation();
const id = btn.dataset.lockId;
const type = btn.dataset.lockType;
const obj = type === "bitmap" ? S.layers.find((l) => l.id === id) : type === "text" ? S.textLayers.find((t) => t.id === id) : S.shapeLayers.find((s) => s.id === id);
if (!obj) return;
saveSnapshot();
obj.locked = !obj.locked;
renderObjects();
renderLayerPanel();
});
});
}
function bindLayerDelButtons(list) {
list.querySelectorAll(".iwb-layer-del").forEach((btn) => {
btn.addEventListener("mousedown", (e) => e.stopPropagation());
btn.addEventListener("click", (e) => {
e.stopPropagation();
const id = btn.dataset.delId;
const type = btn.dataset.delType;
if (type === "bitmap") {
deleteLayer(id);
} else if (type === "text") {
S.selectedTextId = id;
deleteSelectedText();
renderLayerPanel();
} else if (type === "shape") {
S.selectedShapeId = id;
deleteSelectedShape();
renderLayerPanel();
}
});
});
}
var multiKey = (type, id) => type + ":" + id;
function currentUnitRef() {
if (S.selectedLayerId) return { type: "bitmap", id: S.selectedLayerId };
if (S.selectedTextId) return { type: "text", id: S.selectedTextId };
if (S.selectedShapeId) return { type: "shape", id: S.selectedShapeId };
return null;
}
function toggleLayerMulti(type, id) {
const key = multiKey(type, id);
const i = S.layerMulti.findIndex((x) => multiKey(x.type, x.id) === key);
if (i >= 0) {
S.layerMulti.splice(i, 1);
return;
}
if (!S.layerMulti.length) {
const cur = currentUnitRef();
if (cur && multiKey(cur.type, cur.id) !== key) S.layerMulti.push(cur);
}
S.layerMulti.push({ type, id });
}
function composeUnitsInto(layer, units) {
const tmp = document.createElement("canvas");
tmp.width = S.imgW;
tmp.height = S.imgH;
const tctx = tmp.getContext("2d");
for (const u of units) {
const el = u.kind === "bitmap" ? u.obj.canvas : u.obj._canvas;
if (!el || el.nodeType !== 1) continue;
tctx.globalAlpha = u.kind === "bitmap" ? u.obj.opacity == null ? 1 : u.obj.opacity : 1;
tctx.drawImage(el, 0, 0);
}
tctx.globalAlpha = 1;
const ctx = layer.ctx;
ctx.save();
ctx.setTransform(1, 0, 0, 1, 0, 0);
ctx.globalAlpha = 1;
ctx.globalCompositeOperation = "copy";
ctx.filter = "none";
ctx.drawImage(tmp, 0, 0);
ctx.restore();
}
function dropUnit(u) {
if (u.kind === "bitmap") {
const i = S.layers.indexOf(u.obj);
if (i >= 0) S.layers.splice(i, 1);
try {
if (u.obj.canvas && u.obj.canvas.parentNode) u.obj.canvas.parentNode.removeChild(u.obj.canvas);
} catch (e) {
}
} else if (u.kind === "text") {
S.textLayers = S.textLayers.filter((t) => t !== u.obj);
removeVecCanvas(u.obj);
} else if (u.kind === "shape") {
S.shapeLayers = S.shapeLayers.filter((s) => s !== u.obj);
removeVecCanvas(u.obj);
}
}
function mergeUnits(units) {
const sorted = units.slice().sort((a, b) => (a.obj.z || 0) - (b.obj.z || 0));
const lowUnit = sorted[0];
const baseUnit = sorted.find((u) => u.kind === "bitmap" && u.obj.id === "base");
const all = layerUnits();
const lowIdx = all.findIndex((u) => u.obj === lowUnit.obj);
const chosenSet = new Set(sorted.map((u) => u.obj));
const insertAt = all.slice(0, Math.max(lowIdx, 0)).filter((u) => !chosenSet.has(u.obj)).length;
let carrier;
if (baseUnit) {
carrier = baseUnit.obj;
carrier.image = null;
carrier.sourceCanvas = null;
carrier._srcBox = null;
carrier.transformable = false;
carrier.x = 0;
carrier.y = 0;
carrier.w = S.imgW;
carrier.h = S.imgH;
carrier.rotation = 0;
carrier.visible = true;
carrier.opacity = 1;
carrier._bounds = void 0;
composeUnitsInto(carrier, sorted);
for (const u of sorted) if (u.obj !== carrier) dropUnit(u);
const rest = layerUnits().filter((u) => u.obj !== carrier);
rest.unshift({ kind: "bitmap", obj: carrier });
assignLayerZ(rest);
} else {
const canvas = createLayerCanvas();
const ctx = canvas.getContext("2d", { willReadFrequently: true });
carrier = {
id: "m" + Date.now() + Math.floor(Math.random() * 1e3),
name: lowUnit.obj.name || "合并图层",
canvas,
ctx,
opacity: 1,
visible: true,
locked: false,
x: 0,
y: 0,
w: S.imgW,
h: S.imgH,
rotation: 0,
z: lowUnit.obj.z || 0
};
composeUnitsInto(carrier, sorted);
for (const u of sorted) dropUnit(u);
S.layers.push(carrier);
const rest = layerUnits().filter((u) => u.obj !== carrier);
rest.splice(Math.min(insertAt, rest.length), 0, { kind: "bitmap", obj: carrier });
assignLayerZ(rest);
}
S.activeLayerId = carrier.id;
S.selectedLayerId = carrier.id;
S.selectedTextId = null;
S.selectedShapeId = null;
S.textDrag = null;
S.shapeDrag = null;
S.bitmapDrag = null;
S.layerMulti.length = 0;
S.pickerComposite = null;
sortLayersByZ();
reorderLayerCanvas();
updateLayerCanvasStyles();
renderObjects();
renderLayerPanel();
if (S.renderAll) S.renderAll();
return carrier;
}
function mergeLayers() {
const units = layerUnits();
if (units.length < 2) return { ok: false, msg: "只有一个图层,没有可合并的对象" };
let chosen;
if (S.layerMulti.length >= 2) {
chosen = units.filter((u) => S.layerMulti.some((r) => r.type === u.kind && r.id === u.obj.id));
if (chosen.length < 2) return { ok: false, msg: "先选两个以上图层(⌘/Ctrl 点击图层列表)" };
} else {
const cur = currentUnitRef();
const idx = cur ? units.findIndex((u) => u.kind === cur.type && u.obj.id === cur.id) : -1;
if (idx < 0) return { ok: false, msg: "先在图层列表里选中一层" };
if (idx === 0) return { ok: false, msg: "已经是最底层,没有可合并的下一层" };
chosen = [units[idx - 1], units[idx]];
if (chosen[1].obj.visible === false) return { ok: false, msg: "当前层已隐藏,先显示再合并" };
if (chosen[0].obj.visible === false) return { ok: false, msg: "下一层已隐藏,先显示再合并" };
}
const visible = chosen.filter((u) => u.obj.visible !== false);
if (visible.length < 2) return { ok: false, msg: "可见图层不足 2 个,没有可合并的内容" };
saveSnapshot("合并图层");
mergeUnits(visible);
return { ok: true, msg: "已合并 " + visible.length + " 个图层 · Ctrl+Z 撤销" };
}
function mergeVisibleLayers() {
const visible = layerUnits().filter((u) => u.obj.visible !== false);
if (visible.length < 2) return { ok: false, msg: "可见图层不足 2 个,没有可合并的对象" };
saveSnapshot("合并可见图层");
mergeUnits(visible);
return { ok: true, msg: "已合并 " + visible.length + " 个可见图层 · Ctrl+Z 撤销" };
}
// image-annotate/plugin/editor/selection.js
function hasSelection() {
return !!(S.selection && S.selection.active);
}
function selectionInfo() {
if (!hasSelection()) return null;
const b = S.selection.bbox;
return { kind: S.selection.kind, x: Math.round(b.x), y: Math.round(b.y), w: Math.round(b.w), h: Math.round(b.h), feather: S.selection.feather || 0, inverted: !!S.selection.inverted };
}
function clearSelectionCanvas() {
const ctx = S.selectionCtx;
if (!ctx) return;
ctx.save();
ctx.setTransform(1, 0, 0, 1, 0, 0);
ctx.clearRect(0, 0, ctx.canvas.width, ctx.canvas.height);
ctx.restore();
resetOverlayTransform(ctx);
}
function clearCursorCanvas() {
const ctx = S.cursorCtx;
if (!ctx) return;
ctx.save();
ctx.setTransform(1, 0, 0, 1, 0, 0);
ctx.clearRect(0, 0, ctx.canvas.width, ctx.canvas.height);
ctx.restore();
resetOverlayTransform(ctx);
}
function renderSelection() {
if (!S.selectionCtx) return;
clearSelectionCanvas();
const ctx = S.selectionCtx;
const k = 1 / Math.max(viewScale(), 1e-4);
if (S.marquee || S.lassoPts && S.lassoPts.length > 1) {
ctx.save();
ctx.lineWidth = 1.5 * k;
ctx.strokeStyle = "#ffffff";
ctx.setLineDash([5 * k, 4 * k]);
if (S.marquee) {
const b = marqueeBox();
if (S.selectionKind === "ellipse") {
ctx.beginPath();
ctx.ellipse(b.x + b.w / 2, b.y + b.h / 2, Math.max(1, b.w / 2), Math.max(1, b.h / 2), 0, 0, Math.PI * 2);
ctx.stroke();
} else ctx.strokeRect(b.x, b.y, b.w, b.h);
} else {
ctx.beginPath();
ctx.moveTo(S.lassoPts[0].x, S.lassoPts[0].y);
for (let i = 1; i < S.lassoPts.length; i++) ctx.lineTo(S.lassoPts[i].x, S.lassoPts[i].y);
ctx.closePath();
ctx.stroke();
}
ctx.restore();
return;
}
if (!hasSelection()) return;
const p = S.selection.outlinePath || S.selection.path;
ctx.save();
ctx.lineWidth = 1.4 * k;
ctx.setLineDash([5 * k, 5 * k]);
ctx.lineDashOffset = (S._antOffset || 0) * k;
ctx.strokeStyle = "rgba(0,0,0,0.85)";
ctx.stroke(p);
ctx.lineDashOffset = ((S._antOffset || 0) + 5) * k;
ctx.strokeStyle = "rgba(255,255,255,0.95)";
ctx.stroke(p);
ctx.restore();
}
function syncAnts() {
if (hasSelection() && S.open) {
if (!S._antFrame) {
const tick = () => {
S._antOffset = ((S._antOffset || 0) + 0.55) % 10;
renderSelection();
if (S.positionFloating) S.positionFloating();
S._antFrame = requestAnimationFrame(tick);
};
S._antFrame = requestAnimationFrame(tick);
}
} else if (S._antFrame) {
cancelAnimationFrame(S._antFrame);
S._antFrame = 0;
}
}
function rectFromPoints(x0, y0, x1, y1) {
const x = Math.min(x0, x1), y = Math.min(y0, y1);
return { x, y, w: Math.abs(x1 - x0), h: Math.abs(y1 - y0) };
}
function pathForBox(b, kind) {
const p = new Path2D();
if (kind === "ellipse") {
p.ellipse(b.x + b.w / 2, b.y + b.h / 2, Math.max(0.5, b.w / 2), Math.max(0.5, b.h / 2), 0, 0, Math.PI * 2);
} else p.rect(b.x, b.y, Math.max(0.5, b.w), Math.max(0.5, b.h));
return p;
}
function pathForLasso(pts) {
const p = new Path2D();
if (!pts.length) return p;
p.moveTo(pts[0].x, pts[0].y);
for (let i = 1; i < pts.length; i++) p.lineTo(pts[i].x, pts[i].y);
p.closePath();
return p;
}
function bboxOfPoints(pts) {
let minX = Infinity, minY = Infinity, maxX = -Infinity, maxY = -Infinity;
for (const p of pts) {
if (p.x < minX) minX = p.x;
if (p.y < minY) minY = p.y;
if (p.x > maxX) maxX = p.x;
if (p.y > maxY) maxY = p.y;
}
return { x: minX, y: minY, w: Math.max(0, maxX - minX), h: Math.max(0, maxY - minY) };
}
function applyPath(kind, outlinePath, bbox, opts) {
const o = opts || {};
const feather = clamp(Number(S.selectionFeather) || 0, 0, 20);
const inverted = !!o.inverted;
const path = new Path2D();
if (inverted) {
path.rect(0, 0, S.imgW, S.imgH);
path.addPath(outlinePath);
} else {
path.addPath(outlinePath);
}
S.selectedTextId = null;
S.selectedShapeId = null;
S.selection = {
kind,
path,
outlinePath,
bbox,
fillRule: inverted ? "evenodd" : "nonzero",
feather,
inverted,
active: true
};
S.marquee = null;
S.lassoPts = null;
S.interaction = "idle";
if (S.renderAll) S.renderAll();
else renderSelection();
toast(inverted ? "已反选" : "选区 " + Math.round(bbox.w) + "×" + Math.round(bbox.h), "info");
}
function clearMarquee() {
S.selection = null;
S.marquee = null;
S.lassoPts = null;
S.interaction = "idle";
renderSelection();
syncAnts();
if (S.renderAll) S.renderAll();
}
function selectAll() {
const b = { x: 0, y: 0, w: S.imgW, h: S.imgH };
applyPath("rect", pathForBox(b, "rect"), b);
}
function invertSelection() {
if (!hasSelection()) {
toast("先框出一个选区");
return;
}
applyPath(S.selection.kind, S.selection.outlinePath, S.selection.bbox, { inverted: !S.selection.inverted });
}
function marqueeBox() {
const m = S.marquee;
return rectFromPoints(m.x0, m.y0, m.x1, m.y1);
}
function beginMarquee(pos) {
S.selection = null;
S.marquee = { x0: pos.x, y0: pos.y, x1: pos.x, y1: pos.y };
S.interaction = "marquee";
S.isDrawing = true;
renderSelection();
}
function updateMarquee(pos) {
if (!S.marquee) return;
S.marquee.x1 = pos.x;
S.marquee.y1 = pos.y;
renderSelection();
}
function endMarquee() {
const m = S.marquee;
if (!m) return;
const b = marqueeBox();
S.marquee = null;
S.isDrawing = false;
S.interaction = "idle";
if (b.w > 3 && b.h > 3) {
applyPath(S.selectionKind, pathForBox(b, S.selectionKind), b);
} else {
clearMarquee();
}
}
function beginLasso(pos) {
S.selection = null;
S.lassoPts = [{ x: pos.x, y: pos.y }];
S.interaction = "lasso";
S.isDrawing = true;
renderSelection();
}
function updateLasso(pos) {
if (!S.lassoPts) return;
const last = S.lassoPts[S.lassoPts.length - 1];
if (Math.hypot(pos.x - last.x, pos.y - last.y) < 2) return;
S.lassoPts.push({ x: pos.x, y: pos.y });
renderSelection();
}
function endLasso() {
const pts = S.lassoPts;
if (!pts) return;
S.lassoPts = null;
S.isDrawing = false;
S.interaction = "idle";
if (pts.length > 2) {
const b = bboxOfPoints(pts);
if (b.w > 3 && b.h > 3) {
applyPath("lasso", pathForLasso(pts), b);
return;
}
}
clearMarquee();
}
function maskExtent() {
const sel = S.selection;
const b = sel.inverted ? { x: 0, y: 0, w: S.imgW, h: S.imgH } : sel.bbox;
const x = Math.floor(b.x);
const y = Math.floor(b.y);
return {
x,
y,
w: Math.max(1, Math.ceil(b.x + b.w) - x),
h: Math.max(1, Math.ceil(b.y + b.h) - y)
};
}
function buildMask() {
const sel = S.selection;
const feather = sel.feather || 0;
const pad = Math.ceil(feather * 2);
const e = maskExtent();
const w = e.w + pad * 2;
const h = e.h + pad * 2;
const c = document.createElement("canvas");
c.width = w;
c.height = h;
const cx = c.getContext("2d");
cx.save();
cx.translate(-e.x + pad, -e.y + pad);
if (feather > 0) cx.filter = "blur(" + feather + "px)";
cx.fillStyle = "#ffffff";
cx.fill(sel.path, sel.fillRule);
cx.restore();
return { canvas: c, x: e.x - pad, y: e.y - pad, w, h };
}
function writableLayer() {
const layer = getActiveLayer();
if (!layer || layer.locked) {
toast(layer && layer.locked ? "当前图层已锁定,请先解锁" : "没有可用的图层", "warn");
return null;
}
return layer;
}
function eraseOnActiveLayer() {
const layer = writableLayer();
if (!layer) return false;
const mask = buildMask();
layer.ctx.save();
layer.ctx.globalCompositeOperation = "destination-out";
layer.ctx.drawImage(mask.canvas, mask.x, mask.y);
layer.ctx.restore();
layer._bounds = void 0;
S.pickerComposite = null;
mask.canvas.width = 0;
mask.canvas.height = 0;
return true;
}
function copyToLayer(cut) {
const layer = writableLayer();
if (!layer) return false;
const mask = buildMask();
const tile = document.createElement("canvas");
tile.width = mask.w;
tile.height = mask.h;
const tctx = tile.getContext("2d");
tctx.drawImage(layer.canvas, -mask.x, -mask.y);
tctx.globalCompositeOperation = "destination-in";
tctx.drawImage(mask.canvas, 0, 0);
const canvas = createLayerCanvas();
const ctx = canvas.getContext("2d", { willReadFrequently: true });
ctx.drawImage(tile, mask.x, mask.y);
const id = "S" + Date.now() + Math.floor(Math.random() * 1e3);
const fresh = {
id,
name: cut ? "剪切内容" : "选区副本",
canvas,
ctx,
opacity: 1,
visible: true,
locked: false,
transformable: true,
x: 0,
y: 0,
w: S.imgW,
h: S.imgH,
rotation: 0,
z: ++S.zCounter
};
S.layers.push(fresh);
if (cut) eraseOnActiveLayer();
reorderLayerCanvas();
updateLayerCanvasStyles();
setActiveLayer(id);
for (const l of S.layers) l._bounds = void 0;
tile.width = 0;
tile.height = 0;
mask.canvas.width = 0;
mask.canvas.height = 0;
S.pickerComposite = null;
return true;
}
function fillOnActiveLayer() {
const layer = ensureWritableLayer();
if (!layer) return false;
const sel = S.selection;
layer.ctx.save();
if (sel.feather > 0) layer.ctx.filter = "blur(" + sel.feather + "px)";
layer.ctx.globalAlpha = S.brushOpacity;
layer.ctx.fillStyle = S.color;
layer.ctx.fill(sel.path, sel.fillRule);
layer.ctx.restore();
layer._bounds = void 0;
S.pickerComposite = null;
return true;
}
var registered = false;
function registerSelectionCommands() {
if (registered) return;
registered = true;
defineCommand("sel.copy", {
label: "复制为新层",
enabled: hasSelection,
hint: "先框出一个选区",
run: () => {
if (copyToLayer(false)) toast("已复制到新图层", "success");
}
});
defineCommand("sel.cut", {
label: "剪切到新层",
enabled: hasSelection,
hint: "先框出一个选区",
run: () => {
if (copyToLayer(true)) toast("已剪切到新图层", "success");
}
});
defineCommand("sel.delete", {
label: "清除选区内容(当前层)",
enabled: hasSelection,
hint: "先框出一个选区",
run: () => {
if (eraseOnActiveLayer()) toast("已清除当前层选区内容", "success");
}
});
defineCommand("sel.fill", {
label: "填充选区",
enabled: hasSelection,
hint: "先框出一个选区",
run: () => {
if (fillOnActiveLayer()) toast("已填充", "success");
}
});
defineCommand("sel.invert", { label: "反选", view: true, run: invertSelection });
defineCommand("sel.all", { label: "全选", view: true, run: selectAll });
defineCommand("sel.none", { label: "取消选区", view: true, run: clearMarquee });
}
function disposeSelection() {
if (S._antFrame) cancelAnimationFrame(S._antFrame);
S._antFrame = 0;
S.selection = null;
S.marquee = null;
S.lassoPts = null;
clearSelectionCanvas();
clearCursorCanvas();
clearOverlay();
}
// image-annotate/plugin/editor/floating.js
var contextMode = false;
function bar() {
return runtime.el && runtime.el.querySelector(".iwb-editor-sel-bar");
}
function bindFloating() {
const el = bar();
if (!el || el.dataset.bound === "1") return;
el.dataset.bound = "1";
el.addEventListener("mousedown", (e) => e.stopPropagation());
el.addEventListener("click", (e) => {
const btn = e.target.closest("[data-sel-cmd]");
if (!btn) return;
e.stopPropagation();
runCommand(btn.dataset.selCmd);
contextMode = false;
positionFloating();
});
}
function imageToWrap(x, y) {
const stack = S.canvasStack.getBoundingClientRect();
const wrap = S.canvasWrap.getBoundingClientRect();
const scale = S.imgW ? S.fitW * S.zoom / S.imgW : 1;
const pad = S.overlayPad || 0;
return {
x: stack.left - wrap.left + (pad + x) * scale,
y: stack.top - wrap.top + (pad + y) * scale
};
}
function positionFloating() {
const el = bar();
if (!el || !S.open) return;
const active = hasSelection();
if (!active && !contextMode) {
el.style.display = "none";
return;
}
el.style.display = "flex";
el.classList.toggle("as-menu", contextMode);
const wrapW = S.canvasWrap.clientWidth;
const wrapH = S.canvasWrap.clientHeight;
const bw = el.offsetWidth || 300;
const bh = el.offsetHeight || 36;
let left, top;
if (contextMode && el.dataset.cx !== void 0) {
left = Number(el.dataset.cx);
top = Number(el.dataset.cy);
} else {
const b = S.selection.bbox;
const p = imageToWrap(b.x + b.w, b.y + b.h);
left = p.x + 10;
top = p.y + 8;
if (left + bw > wrapW - 8) left = imageToWrap(b.x, b.y).x + b.w * (S.fitW * S.zoom) / S.imgW - bw;
if (top + bh > wrapH - 8) top = imageToWrap(b.x, b.y).y - bh - 8;
}
el.style.left = Math.max(8, Math.min(left, Math.max(8, wrapW - bw - 8))) + "px";
el.style.top = Math.max(8, Math.min(top, Math.max(8, wrapH - bh - 8))) + "px";
el.querySelectorAll("[data-sel-cmd]").forEach((btn) => {
const need = btn.dataset.needsSel === "1";
btn.disabled = need && !active;
});
const info = el.querySelector(".iwb-editor-sel-info");
if (info) {
const s = selectionInfo();
info.textContent = s ? s.w + "×" + s.h + (s.feather ? " · 羽化 " + s.feather : "") : "未框选";
}
}
function showSelectionContext(e) {
const el = bar();
if (!el) return;
const wrap = S.canvasWrap.getBoundingClientRect();
contextMode = true;
el.dataset.cx = String(e.clientX - wrap.left);
el.dataset.cy = String(e.clientY - wrap.top);
positionFloating();
if (!hasSelection()) toast("右键菜单:可先「全选」,或框选后直接操作", "info");
}
function hideSelectionContext() {
if (!contextMode) return;
contextMode = false;
const el = bar();
if (el) el.classList.remove("as-menu");
positionFloating();
}
// image-annotate/plugin/editor/dom.js
function createEl() {
if (runtime.el) return;
runtime.el = document.createElement("div");
runtime.el.id = "iwb-editor-overlay";
runtime.el.className = "iwb-editor-overlay";
runtime.el.innerHTML = `
<div class="iwb-editor-modal">
<div class="iwb-editor-header">
<span class="iwb-editor-title">图片编辑 <em class="iwb-editor-doc-size">—</em></span>
<!-- 会话组(v1.2.9):标题是标题、按钮是按钮 —— 新建/覆盖/退出跟在标题后(用户裁定 2026-11-04 晚) -->
<div class="iwb-editor-session">
<button class="iwb-editor-btn iwb-editor-btn-new" data-action="newNode" title="把当前编辑结果新建为节点(不关闭编辑器)">新建</button>
<button class="iwb-editor-btn iwb-editor-btn-replace" data-action="replace" title="用当前编辑结果覆盖原图">覆盖</button>
<button class="iwb-editor-btn iwb-editor-btn-cancel" data-action="cancel" title="放弃修改并退出">退出</button>
</div>
<div class="iwb-editor-history">
<button class="iwb-editor-action" data-action="undo" title="撤销 (Ctrl+Z)"><svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><polyline points="1 4 1 10 7 10"/><path d="M3.51 15a9 9 0 1 0 2.13-9.36L1 10"/></svg></button>
<button class="iwb-editor-action" data-action="redo" title="重做 (Ctrl+Shift+Z)"><svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><polyline points="23 4 23 10 17 10"/><path d="M20.49 15a9 9 0 1 1-2.12-9.36L23 10"/></svg></button>
<button class="iwb-editor-action iwb-editor-action-reset" data-action="reset" title="还原原图:删掉所有标注/图层,回到打开时的样子(Ctrl+Z 可撤销)"><svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M21 2v6h-6"/><path d="M3 12a9 9 0 0 1 15-6.7L21 8"/><path d="M3 22v-6h6"/><path d="M21 12a9 9 0 0 1-15 6.7L3 16"/></svg></button>
</div>
<span class="iwb-editor-divider"></span>
<!-- 顶栏命令带(v1.2.6):撤销/重做/还原 | 顺序 | 视图;图层新建/导入回图层面板标题栏 -->
<div class="iwb-editor-commands">
<div class="iwb-editor-cmdgroup" data-group="order" title="调整选中元素的图层顺序">
<button class="iwb-editor-layer-btn" data-layer="top" title="置顶:选中元素移到最上层 (Ctrl+Shift+])"><svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><line x1="4" y1="5" x2="20" y2="5"/><line x1="12" y1="19" x2="12" y2="5"/><polyline points="6 11 12 5 18 11"/></svg></button>
<button class="iwb-editor-layer-btn" data-layer="up" title="上移一层 (Ctrl+])"><svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><line x1="12" y1="19" x2="12" y2="5"/><polyline points="6 11 12 5 18 11"/></svg></button>
<button class="iwb-editor-layer-btn" data-layer="down" title="下移一层 (Ctrl+[)"><svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><line x1="12" y1="5" x2="12" y2="19"/><polyline points="6 13 12 19 18 13"/></svg></button>
<button class="iwb-editor-layer-btn" data-layer="bottom" title="置底:选中元素移到最下层 (Ctrl+Shift+[)"><svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><line x1="12" y1="5" x2="12" y2="19"/><polyline points="6 13 12 19 18 13"/><line x1="4" y1="19" x2="20" y2="19"/></svg></button>
</div>
<span class="iwb-editor-divider"></span>
<div class="iwb-editor-cmdgroup" data-group="view">
<button class="iwb-editor-action" data-action="zoomFit" title="适应窗口 (Ctrl+0)"><svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><polyline points="9 3 3 3 3 9"/><polyline points="15 3 21 3 21 9"/><polyline points="3 15 3 21 9 21"/><polyline points="21 15 21 21 15 21"/></svg></button>
<button class="iwb-editor-action" data-action="togglePanels" title="收起 / 展开侧栏 (Tab)"><svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><rect x="3" y="4" width="18" height="16" rx="2"/><line x1="9" y1="4" x2="9" y2="20"/></svg></button>
</div>
</div>
<div class="iwb-editor-export-actions">
<div class="iwb-editor-export-settings-wrap">
<button class="iwb-editor-export-settings-btn" data-action="toggleExportSettings" aria-expanded="false">输出 <span class="iwb-editor-export-summary">原尺寸 PNG</span> ▾</button>
<div class="iwb-editor-export-settings">
<div class="iwb-editor-export-row"><span>预设</span>
<button data-export-key="preset" data-export-value="original">原尺寸</button>
<button data-export-key="preset" data-export-value="ecom800">电商方图</button>
</div>
<div class="iwb-editor-export-row"><span>格式</span>
<button data-export-key="format" data-export-value="png">PNG</button>
<button data-export-key="format" data-export-value="jpeg">JPG</button>
<button data-export-key="format" data-export-value="webp">WebP</button>
</div>
<div class="iwb-editor-export-row"><span>背景</span>
<button data-export-key="bg" data-export-value="transparent">透明</button>
<button data-export-key="bg" data-export-value="white">白底</button>
</div>
<div class="iwb-editor-export-row" data-export-when="ecom800"><span>边长</span>
<button data-export-key="size" data-export-value="750">750</button>
<button data-export-key="size" data-export-value="800">800</button>
<button data-export-key="size" data-export-value="1000">1000</button>
<button data-export-key="size" data-export-value="1200">1200</button>
</div>
<div class="iwb-editor-export-row" data-export-when="ecom800" title="商品图体积上限(仅对 JPG / WebP 生效,PNG 无法降质)"><span>≤KB</span>
<button data-export-key="maxKB" data-export-value="0">不限</button>
<button data-export-key="maxKB" data-export-value="300">300</button>
<button data-export-key="maxKB" data-export-value="500">500</button>
<button data-export-key="maxKB" data-export-value="800">800</button>
</div>
<div class="iwb-editor-export-note">一次只输出一个结果;设置会记住</div>
</div>
</div>
<button class="iwb-editor-btn iwb-editor-btn-copy" data-action="copyClipboard" title="复制当前结果到系统剪贴板(可直接粘到聊天窗口/后台),不关闭编辑器">复制</button>
<button class="iwb-editor-btn iwb-editor-btn-download" data-action="download" title="导出当前这一张(不关闭编辑器)">导出</button>
</div>
</div>
<div class="iwb-editor-optionbar">
<span class="iwb-editor-optionbar-label">工具选项</span>
<div class="iwb-editor-optionbar-body"></div>
<span class="iwb-editor-optionbar-tip" title="选中后还可右键;Ctrl+J 复制 · Delete 清除 · Ctrl+D 取消选区">Ctrl+J 复制 · Delete 清除</span>
</div>
<div class="iwb-editor-main">
<div class="iwb-editor-layer-panel">
<div class="iwb-editor-layer-panel-header">
<span class="iwb-editor-layer-panel-title">图层</span>
<!-- 图层的「新建 / 导入图片」回到标题栏右侧(用户裁定 2026-11-04:顶栏只留顺序与视图命令) -->
<div class="iwb-editor-layer-add-group">
<button class="iwb-editor-layer-add-btn" data-action="mergeLayers" title="合并图层 (Ctrl/⌘+E):⌘/Ctrl 点击可多选图层后合并;未多选时向下合并"><svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="m12 2 9 4.5-9 4.5-9-4.5L12 2Z"/><path d="m3 12 9 4.5 9-4.5"/><path d="M12 17v4"/><path d="m9.5 18.5 2.5 2.5 2.5-2.5"/></svg></button>
<button class="iwb-editor-layer-add-btn" data-action="mergeVisible" title="合并可见图层 (Ctrl/⌘+Shift+E):隐藏的图层保留不动"><svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="m12 2 9 4.5-9 4.5-9-4.5L12 2Z"/><path d="m3 11 9 4.5 9-4.5"/><path d="m3 15.5 9 4.5 9-4.5"/></svg></button>
<button class="iwb-editor-layer-add-btn" data-action="addBlankLayer" title="新建空白图层 (Ctrl+Shift+N)"><svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><rect x="3" y="3" width="18" height="18" rx="2"/><line x1="12" y1="8" x2="12" y2="16"/><line x1="8" y1="12" x2="16" y2="12"/></svg></button>
<button class="iwb-editor-layer-add-btn" data-action="addBitmapLayer" title="导入图片为新图层 (Ctrl+O),也可直接 ⌘/Ctrl+V 粘贴剪贴板图片"><svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><rect x="3" y="3" width="18" height="18" rx="2"/><circle cx="9" cy="9" r="2"/><path d="m21 15-3.1-3.1a2 2 0 0 0-2.8 0L6 21"/><line x1="19" y1="8" x2="19" y2="14"/><line x1="22" y1="11" x2="16" y2="11"/></svg></button>
</div>
</div>
<!-- 图层顺序(置顶/上移/下移/置底)已移到顶栏命令带(v1.2.4) -->
<div class="iwb-editor-layer-list"></div>
</div>
<div class="iwb-editor-canvas-wrap">
<div class="iwb-editor-canvas-stack">
<div class="iwb-editor-transparency-grid"></div>
<!-- 位图图层 canvas 动态插入此处 -->
<canvas class="iwb-editor-stroke"></canvas>
<canvas class="iwb-editor-text"></canvas>
<canvas class="iwb-editor-crop-overlay"></canvas>
<canvas class="iwb-editor-selection-overlay"></canvas>
<canvas class="iwb-editor-cursor-overlay"></canvas>
</div>
<!-- v1.9:input → textarea,支持 Shift+Enter 换行(Enter 仍是确认) -->
<textarea class="iwb-editor-text-input" rows="1" wrap="off" placeholder="输入文字,Enter 确认,Shift+Enter 换行" spellcheck="false"></textarea>
<div class="iwb-editor-picker-tip"><span class="iwb-editor-picker-chip"></span><span class="iwb-editor-picker-hex">#ffffff</span></div>
<!-- 裁剪参数已迁入选项栏(v1.2.2),画布下方浮窗删除 -->
<div class="iwb-editor-sel-bar">
<span class="iwb-editor-sel-info">未框选</span>
<button data-sel-cmd="sel.copy" data-needs-sel="1" title="把当前图层选区复制为新图层 (Ctrl+J)">复制</button>
<button data-sel-cmd="sel.cut" data-needs-sel="1" title="剪切到新图层 (Ctrl+X)">剪切</button>
<button data-sel-cmd="sel.delete" data-needs-sel="1" title="只清除当前图层选区内容 (Delete)">删除</button>
<button data-sel-cmd="sel.fill" data-needs-sel="1" title="用当前颜色填充选区">填充</button>
<button data-sel-cmd="sel.invert" data-needs-sel="1" title="反选 (Ctrl+Shift+I)">反选</button>
<button data-sel-cmd="sel.all" title="全选 (Ctrl+A)">全选</button>
<button data-sel-cmd="sel.none" title="取消选区 (Esc / Ctrl+D)">取消</button>
</div>
<div class="iwb-editor-tools">
<!-- 当前色圆点(v1.3):点开就是完整色板,侧栏不再放调色板 -->
<button type="button" class="iwb-editor-color-btn" data-action="toggleColorPop" aria-expanded="false" title="颜色:点开色板(调色器 / 吸管 / 推荐色)"><i></i></button>
<span class="iwb-editor-divider"></span>
<button class="iwb-editor-tool" data-tool="select" title="选择/移动 (V):点击元素选中,拖拽移动,手柄调整大小,双击文字改内容"><svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M3 3l7.07 16.97 2.51-7.39 7.39-2.51L3 3z"/></svg></button>
<span class="iwb-editor-divider"></span>
<button class="iwb-editor-tool" data-tool="marquee" title="选框 (M):拖出矩形/椭圆选区,松手后旁边出现操作条;Shift+M 切换矩形/椭圆"><svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" stroke-dasharray="4 3"><rect x="3" y="4" width="18" height="16" rx="1"/></svg></button>
<button class="iwb-editor-tool" data-tool="lasso" title="套索 (L):按住拖动自由圈选,松手闭合"><svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M4 12c0-4 3.6-7 8-7s8 3 8 7-3.6 7-8 7c-2 0-3.8-.6-5.2-1.6"/><path d="M6.8 17.4 4 20l1.2-3.2"/><circle cx="20" cy="19" r="2"/></svg></button>
<button class="iwb-editor-tool active" data-tool="brush" title="画笔 (B):] 增大 / [ 减小笔刷;按住 Alt 临时吸色"><svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M17 3a2.85 2.83 0 1 1 4 4L7.5 20.5 2 22l1.5-5.5Z"/><path d="m15 5 4 4"/></svg></button>
<button class="iwb-editor-tool" data-tool="eraser" title="橡皮 (E):] 增大 / [ 减小笔刷;擦除当前活跃图层,与画笔共用大小/硬度/透明度;按住 Alt 临时吸色"><svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="m7 21-4.3-4.3c-1-1-1-2.5 0-3.4l9.6-9.6c1-1 2.5-1 3.4 0l5.6 5.6c1 1 1 2.5 0 3.4L13 21"/><path d="M22 21H7"/><path d="m5 11 9 9"/></svg></button>
<button class="iwb-editor-tool" data-tool="pen" title="钢笔 (P):点击添加节点,双击或 Enter 完成自定义形状"><svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="m12 19 7-7 3 3-7 7-3-3z"/><path d="m18 13-1.5-7.5L2 2l3.5 14.5L13 18l5-5z"/><path d="m2 2 7.586 7.586"/><circle cx="11" cy="11" r="2"/></svg></button>
<button class="iwb-editor-tool" data-tool="text" title="文字 (T)"><svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><polyline points="4 7 4 3 20 3 20 7"/><line x1="9" y1="20" x2="15" y2="20"/><line x1="12" y1="3" x2="12" y2="20"/></svg></button>
<button class="iwb-editor-tool" data-tool="rect" title="矩形 (U):Shift+U 在矩形/圆形/箭头间循环"><svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><rect x="3" y="3" width="18" height="18" rx="2"/></svg></button>
<button class="iwb-editor-tool" data-tool="circle" title="圆形 (U):Shift+U 在矩形/圆形/箭头间循环"><svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><circle cx="12" cy="12" r="8"/></svg></button>
<button class="iwb-editor-tool" data-tool="arrow" title="箭头 (U):Shift+U 在矩形/圆形/箭头间循环"><svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><line x1="5" y1="12" x2="19" y2="12"/><polyline points="12 5 19 12 12 19"/></svg></button>
<button class="iwb-editor-tool" data-tool="picker" title="吸管 (I):点击画布取色(悬停预览);选中形状/文字时取色直接改它的颜色,取完切回上一工具"><svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="m2 22 1-1h3l9-9"/><path d="M3 21v-3l9-9"/><path d="m15 6 3.4-3.4a2.1 2.1 0 1 1 3 3L18 9l.4.4a2.1 2.1 0 1 1-3 3l-3.8-3.8a2.1 2.1 0 1 1 3-3Z"/></svg></button>
<button class="iwb-editor-tool" data-tool="hand" title="抓手 (H):拖拽自由移动画布(任意工具下按住空格或鼠标中键也可平移)"><svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M18 11V6a2 2 0 0 0-2-2v0a2 2 0 0 0-2 2v0"/><path d="M14 10V4a2 2 0 0 0-2-2v0a2 2 0 0 0-2 2v2"/><path d="M10 10.5V6a2 2 0 0 0-2-2v0a2 2 0 0 0-2 2v8"/><path d="M18 10a2 2 0 1 1 4 0v3a8 8 0 0 1-8 8h-2c-2.8 0-4.5-.86-5.99-2.34l-3.6-3.6a2 2 0 0 1 2.83-2.82L7 15"/></svg></button>
<span class="iwb-editor-divider"></span>
<button class="iwb-editor-tool" data-tool="crop" title="裁剪 (C):参数在选项栏;Enter 确认 / Esc 取消"><svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M6.13 1L6 16a2 2 0 0 0 2 2h15"/><path d="M1 6.13L16 6a2 2 0 0 1 2 2v15"/></svg></button>
<span class="iwb-editor-divider"></span>
</div>
</div>
<div class="iwb-editor-zoom-hint">滚轮缩放 · 抓手/空格/中键拖拽自由移动画布</div>
<aside class="iwb-editor-left">
<!-- 调色板已迁到工具栏弹层(v1.3,用户裁定 2026-11-05):
侧栏只留快速效果 + 缩放;色板 DOM 在 modal 末尾的 .iwb-editor-color-pop -->
<!-- 快速效果(v1.4):作用于当前位图图层,点一下就应用,Ctrl+Z 撤销。
目标层名由 effects.js 的 updateFxTargetLabel() 实时刷新。 -->
<section class="iwb-editor-fx">
<div class="iwb-editor-fx-head">
<span class="iwb-editor-fx-title">快速效果</span>
<span class="iwb-editor-fx-target" title="效果作用于当前位图图层">原图</span>
</div>
<div class="iwb-editor-fx-grid">
<button type="button" class="iwb-editor-fx-btn" data-fx="invert" title="反白(反相 Invert):明暗翻转,白底变黑底、黑字变白字">
<span class="iwb-editor-fx-ico ico-invert"></span><span>反白</span>
</button>
<button type="button" class="iwb-editor-fx-btn" data-fx="gray" title="灰度:去色,保留明暗层次">
<span class="iwb-editor-fx-ico ico-gray"></span><span>灰度</span>
</button>
<button type="button" class="iwb-editor-fx-btn" data-fx="boost" title="增强:提亮并略加对比,适合发灰的截图">
<span class="iwb-editor-fx-ico ico-boost"></span><span>增强</span>
</button>
<button type="button" class="iwb-editor-fx-btn" data-fx="contrast" title="高对比:压成黑白硬调,突出主体">
<span class="iwb-editor-fx-ico ico-contrast"></span><span>高对比</span>
</button>
<button type="button" class="iwb-editor-fx-btn" data-fx="soft" title="柔化:轻微模糊,弱化背景">
<span class="iwb-editor-fx-ico ico-soft"></span><span>柔化</span>
</button>
<button type="button" class="iwb-editor-fx-btn" data-fx="mosaic" title="马赛克:像素化,用于打码手机号/地址等隐私信息">
<span class="iwb-editor-fx-ico ico-mosaic"></span><span>马赛克</span>
</button>
</div>
<!-- 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">
<button class="iwb-editor-zoom-btn" data-action="zoomOut" title="缩小 (Ctrl+- / 滚轮向下)">−</button>
<span class="iwb-editor-zoom-val" title="滚轮缩放">100%</span>
<button class="iwb-editor-zoom-btn" data-action="zoomIn" title="放大 (Ctrl++ / 滚轮向上)">+</button>
<button class="iwb-editor-zoom-btn iwb-editor-zoom-fit" data-action="zoomFit" title="适应窗口">适应</button>
</div>
</aside>
</div>
<div class="iwb-editor-footer">
</div>
<div class="iwb-editor-statusbar">
<span class="iwb-editor-status-zoom">100%</span>
<span class="iwb-editor-status-size">—</span>
<span class="iwb-editor-status-pos">x — y —</span>
<span class="iwb-editor-status-sel">无选区</span>
<span class="iwb-editor-status-layer">当前层:原图</span>
<span class="iwb-editor-status-tool">画笔</span>
</div>
<!-- 色板弹层(v1.3):工具栏色点点击展开。
必须挂在 modal 下、不能塞进 .iwb-editor-tools —— 工具栏是 overflow-x:auto,
canvas-wrap 是 overflow:clip,塞进去弹层会被直接裁掉;定位由 events.js 计算。 -->
<div class="iwb-editor-color-pop" hidden>
<div class="iwb-color-pop-picker">
<div class="iwb-color-sv"><span></span></div>
<div class="iwb-color-hue"><span></span></div>
</div>
<span class="iwb-color-pop-sep"></span>
<div class="iwb-color-pop-fields">
<button type="button" class="iwb-editor-color-eye" data-action="palettePick" title="吸色:切到吸管工具,在画布上点一下取色"><svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="m2 22 1-1h3l9-9"/><path d="M3 21v-3l9-9"/><path d="m15 6 3.4-3.4a2.1 2.1 0 1 1 3 3L18 9l.4.4a2.1 2.1 0 1 1-3 3l-3.8-3.8a2.1 2.1 0 1 1 3-3Z"/></svg></button>
<input class="iwb-editor-color-hex-input" value="#ff4444" maxlength="7" spellcheck="false" autocomplete="off" title="十六进制颜色,回车生效">
</div>
<span class="iwb-color-pop-sep"></span>
<!-- 最近使用(v1.9):由 recent-colors.js 动态填充,空的时候整行隐藏 -->
<div class="iwb-editor-recent-colors" hidden title="最近使用"></div>
<div class="iwb-editor-color-swatches">
<button type="button" class="iwb-editor-color-panel-swatch" data-panel-color="#ff4444" style="background:#ff4444" title="#ff4444"></button>
<button type="button" class="iwb-editor-color-panel-swatch" data-panel-color="#ff8a00" style="background:#ff8a00" title="#ff8a00"></button>
<button type="button" class="iwb-editor-color-panel-swatch" data-panel-color="#ffd400" style="background:#ffd400" title="#ffd400"></button>
<button type="button" class="iwb-editor-color-panel-swatch" data-panel-color="#4cd964" style="background:#4cd964" title="#4cd964"></button>
<button type="button" class="iwb-editor-color-panel-swatch" data-panel-color="#00bfa5" style="background:#00bfa5" title="#00bfa5"></button>
<button type="button" class="iwb-editor-color-panel-swatch" data-panel-color="#4488ff" style="background:#4488ff" title="#4488ff"></button>
<button type="button" class="iwb-editor-color-panel-swatch" data-panel-color="#aa44ff" style="background:#aa44ff" title="#aa44ff"></button>
<button type="button" class="iwb-editor-color-panel-swatch" data-panel-color="#ff66aa" style="background:#ff66aa" title="#ff66aa"></button>
<button type="button" class="iwb-editor-color-panel-swatch" data-panel-color="#ffffff" style="background:#ffffff" title="#ffffff"></button>
<button type="button" class="iwb-editor-color-panel-swatch" data-panel-color="#d0d0d0" style="background:#d0d0d0" title="#d0d0d0"></button>
<button type="button" class="iwb-editor-color-panel-swatch" data-panel-color="#808080" style="background:#808080" title="#808080"></button>
<button type="button" class="iwb-editor-color-panel-swatch" data-panel-color="#000000" style="background:#000000" title="#000000"></button>
</div>
</div>
<div class="iwb-editor-toast" role="status" aria-live="polite"></div>
</div>
`;
document.body.appendChild(runtime.el);
S.canvasWrap = runtime.el.querySelector(".iwb-editor-canvas-wrap");
S.canvasStack = runtime.el.querySelector(".iwb-editor-canvas-stack");
S.transparencyGrid = runtime.el.querySelector(".iwb-editor-transparency-grid");
S.textCanvas = runtime.el.querySelector(".iwb-editor-text");
S.strokeCanvas = runtime.el.querySelector(".iwb-editor-stroke");
S.overlayCanvas = runtime.el.querySelector(".iwb-editor-crop-overlay");
S.selectionCanvas = runtime.el.querySelector(".iwb-editor-selection-overlay");
S.cursorCanvas = runtime.el.querySelector(".iwb-editor-cursor-overlay");
S.textCtx = S.textCanvas.getContext("2d");
S.strokeCtx = S.strokeCanvas.getContext("2d");
S.overlayCtx = S.overlayCanvas.getContext("2d");
S.selectionCtx = S.selectionCanvas.getContext("2d");
S.cursorCtx = S.cursorCanvas.getContext("2d");
bindEvents();
}
function dataUrlToBlob(dataUrl) {
const comma = dataUrl.indexOf(",");
if (comma < 0) return null;
const meta = dataUrl.slice(0, comma);
if (!/;base64/i.test(meta)) return null;
const mime = (/^data:([^;,]+)/.exec(meta) || [])[1] || "image/png";
const bin = atob(dataUrl.slice(comma + 1));
const bytes = new Uint8Array(bin.length);
for (let i = 0; i < bin.length; i++) bytes[i] = bin.charCodeAt(i);
return new Blob([bytes], { type: mime });
}
async function loadImage(src) {
let useSrc = src;
let revokeUrl = null;
if (typeof src === "string" && src.slice(0, 5) === "data:") {
try {
const blob = dataUrlToBlob(src);
if (!blob) throw new Error("dataURL 不是 base64");
useSrc = URL.createObjectURL(blob);
revokeUrl = useSrc;
} catch (e) {
useSrc = src;
}
}
try {
return await new Promise((resolve, reject) => {
const img = new Image();
img.onload = () => resolve(img);
img.onerror = () => reject(new Error("图片加载失败"));
img.src = useSrc;
});
} finally {
if (revokeUrl) {
try {
URL.revokeObjectURL(revokeUrl);
} catch (e) {
}
}
}
}
// image-annotate/plugin/editor/effects.js
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 / 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;
return S.layers.find((l) => l.id === "base") || null;
}
function filterCanvas(canvas, css) {
const w = canvas.width, h = canvas.height;
if (!w || !h || !css) return;
const tmp = document.createElement("canvas");
tmp.width = w;
tmp.height = h;
const tctx = tmp.getContext("2d");
tctx.filter = css;
tctx.drawImage(canvas, 0, 0);
const ctx = canvas.getContext("2d");
ctx.save();
ctx.setTransform(1, 0, 0, 1, 0, 0);
ctx.globalAlpha = 1;
ctx.globalCompositeOperation = "copy";
ctx.filter = "none";
ctx.drawImage(tmp, 0, 0);
ctx.restore();
}
function pixelateCanvas(canvas, block) {
const w = canvas.width, h = canvas.height;
if (!w || !h) return;
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;
const tctx = tmp.getContext("2d");
tctx.imageSmoothingEnabled = true;
tctx.drawImage(canvas, 0, 0, sw, sh);
const ctx = canvas.getContext("2d");
ctx.save();
ctx.setTransform(1, 0, 0, 1, 0, 0);
ctx.globalAlpha = 1;
ctx.globalCompositeOperation = "copy";
ctx.imageSmoothingEnabled = false;
ctx.filter = "none";
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 });
ctx.clearRect(0, 0, S.imgW, S.imgH);
ctx.drawImage(layer.canvas, 0, 0);
const units = layerUnits();
const i = units.findIndex((u) => u.kind === "bitmap" && u.obj === layer);
const baseZ = layer.z || 0;
const nextZ = i >= 0 && units[i + 1] ? units[i + 1].obj.z || 0 : baseZ + 1;
const z = nextZ > baseZ ? (baseZ + nextZ) / 2 : baseZ + 0.5;
const clone = {
id: "fx" + Date.now() + Math.floor(Math.random() * 1e3),
name: layer.name + " · 效果",
canvas,
ctx,
opacity: layer.opacity == null ? 1 : layer.opacity,
visible: true,
locked: false,
x: 0,
y: 0,
w: S.imgW,
h: S.imgH,
rotation: 0,
z
};
S.layers.push(clone);
layer.visible = false;
if (S.selectedLayerId === layer.id) S.selectedLayerId = clone.id;
S.activeLayerId = clone.id;
reorderLayerCanvas();
updateLayerCanvasStyles();
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;
const layer = effectTarget();
if (!layer) {
toast("没有可处理的图层");
return false;
}
if (layer.visible === false) {
toast("「" + layer.name + "」已隐藏,先显示再应用效果");
return false;
}
let target = layer;
if (!needsPixelSnapshot(layer)) target = rasterizeLayer(layer);
if (!target) {
toast("栅格化失败,效果未应用");
return false;
}
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();
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;
}
// image-annotate/plugin/editor/events.js
var MOUSE_DOWN_HANDLERS = {
select: onSelectMouseDown,
crop: onCropMouseDown,
text: onTextMouseDown,
picker: onPickerMouseDown,
brush: onBrushMouseDown,
eraser: onEraserMouseDown,
pen: onPenMouseDown,
rect: onShapeMouseDown,
arrow: onShapeMouseDown,
circle: onShapeMouseDown
};
function onMouseDown(e) {
if (S.placingImage) {
onPlacementMouseDown(e);
return;
}
if (S.spaceDown || S.tool === "hand" || e.button === 1) {
onPanMouseDown(e);
return;
}
if (e.button !== 0) return;
e.preventDefault();
const pos = getPos(e);
S.startX = pos.x;
S.startY = pos.y;
hideSelectionContext();
if (S.layerMulti.length) {
S.layerMulti.length = 0;
renderLayerPanel();
}
if (S.tool === "marquee") {
beginMarquee(pos);
return;
}
if (S.tool === "lasso") {
beginLasso(pos);
return;
}
const dbl = isDoubleClick(pos);
if (S.tool === "select") {
if (dbl && onCanvasDoubleClick(e, pos)) return;
const penShape = getPenEditingShape();
if (penShape && onPenEditMouseDown(e, pos, penShape)) return;
}
if (S.tool === "pen" && dbl) {
commitPenPath();
return;
}
const handler = Object.prototype.hasOwnProperty.call(MOUSE_DOWN_HANDLERS, S.tool) ? MOUSE_DOWN_HANDLERS[S.tool] : null;
if (handler) handler(pos, e);
}
var DBL_INTERVAL = 380;
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 / 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 / viewScale(), 8));
if (pi < 0) return false;
e.preventDefault();
saveSnapshot();
const pts = penShape.pts;
const minPts = penShape.closed ? 3 : 2;
if (pts.length <= minPts) {
removeVecCanvas(penShape);
S.shapeLayers = S.shapeLayers.filter((x) => x.id !== penShape.id);
S.penEditId = null;
S.selectedShapeId = null;
} else {
pts.splice(pi, 1);
if (penShape.closed && pts.length < 3) penShape.closed = false;
}
renderObjects();
renderLayerPanel();
return true;
}
const hitPen = hitShapeLayer(pos, true);
if (hitPen && hitPen.type === "pen") {
e.preventDefault();
beginPenEdit(hitPen);
return true;
}
const hitText = hitTextLayer(pos);
if (hitText) {
e.preventDefault();
selectUnit("text", hitText.id);
if (hitText.locked) return true;
renderObjects();
showTextInput(hitText.x, hitText.y, hitText);
return true;
}
return false;
}
function onPlacementMouseDown(e) {
e.preventDefault();
const pos = getPos(e);
const handle = hitPlacementHandle(pos);
if (handle) {
S.placingHandle = handle;
S.placingStart = { mx: pos.x, my: pos.y, x: S.placingImage.x, y: S.placingImage.y, w: S.placingImage.w, h: S.placingImage.h, rotation: S.placingImage.rotation || 0 };
S.drawCanvasCursor(CROP_CURSORS[handle] || "move");
return;
}
if (insidePlacementRect(pos)) {
S.placingHandle = "move";
S.placingStart = { mx: pos.x, my: pos.y, x: S.placingImage.x, y: S.placingImage.y, rotation: S.placingImage.rotation || 0 };
S.drawCanvasCursor("move");
return;
}
confirmImagePlacement();
}
function onPanMouseDown(e) {
e.preventDefault();
commitTextInput();
S.panning = true;
S.panStart = { x: e.clientX, y: e.clientY, vx: S.viewX || 0, vy: S.viewY || 0 };
updateCursor();
}
function onPenEditMouseDown(e, pos, penShape) {
const pi = hitPenPoint(pos, penShape, Math.max(16 / viewScale(), 9));
if (pi >= 0) {
S.penDragPt = pi;
S.penDragBase = JSON.parse(JSON.stringify(penShape.pts));
S.penDragPending = snapshotState();
return true;
}
const ei = hitPenEdgeInsert(pos, penShape);
if (ei >= 0) {
saveSnapshot();
penShape.pts.splice(ei + 1, 0, { x: pos.x, y: pos.y });
renderObjects();
renderLayerPanel();
return true;
}
S.penEditId = null;
S.penDragPt = -1;
S.penDragPending = null;
renderObjects();
return false;
}
function onSelectMouseDown(pos) {
if (commitTextInput()) return;
const bitmapHandle = hitBitmapHandle(pos);
if (bitmapHandle) {
beginBitmapDrag(bitmapHandle, pos);
return;
}
const th = hitTextHandle(pos);
if (th) {
if (th === "rotate") beginTextRotate(pos);
else beginTextScaleDrag(th, pos);
return;
}
const shH = hitShapeHandle(pos);
if (shH) {
beginShapeHandleDrag(shH, pos);
return;
}
const hit = hitTopmost(pos);
if (!hit) {
selectUnit(null, null);
renderObjects();
renderLayerPanel();
return;
}
selectUnit(hit.kind, hit.obj.id);
if (hit.obj.locked) {
renderObjects();
renderLayerPanel();
return;
}
if (hit.kind === "bitmap") {
S.activeLayerId = hit.obj.id;
beginBitmapDrag(null, pos);
} else if (hit.kind === "text") {
S.textDrag = { mode: "move", start: pos, layer: { x: hit.obj.x, y: hit.obj.y }, pending: snapshotState() };
} else {
S.shapeDrag = { mode: "move", start: pos, shape: { ...hit.obj }, pending: snapshotState() };
}
renderObjects();
renderLayerPanel();
}
function onCropMouseDown(pos) {
if (S.cropRect) {
const handle = hitCropHandle(pos);
if (handle) {
S.cropHandle = handle;
S.isDrawing = true;
return;
}
if (insideRect(pos, S.cropRect)) {
S.cropMoving = true;
S.moveStart = { x: pos.x, y: pos.y, rect: { ...S.cropRect } };
S.isDrawing = true;
}
return;
}
S.isDrawing = true;
}
function onTextMouseDown(pos) {
if (commitTextInput()) return;
if (S.selectedTextId) {
S.selectedTextId = null;
renderObjects();
renderLayerPanel();
}
showTextInput(pos.x, pos.y);
}
function onPickerMouseDown(pos) {
const s = sampleColor(pos);
if (s && s.a > 0) {
applyColorChange(rgbToHex(s.r, s.g, s.b));
}
exitPicker();
return;
}
function onBrushMouseDown(pos) {
const layer = ensureWritableLayer();
if (!layer) return;
S.selectedLayerId = layer.id;
S.isDrawing = true;
saveSnapshot();
beginStroke();
strokeSegment(pos.x, pos.y, pos.x, pos.y);
}
function onEraserMouseDown(pos) {
let layer = getActiveLayer();
if (!layer || layer.locked) layer = topWritableLayer();
if (!layer) {
toast("没有可擦的图层:先用画笔标注,或在图层面板新建一层", "info");
return;
}
S.activeLayerId = layer.id;
S.selectedLayerId = layer.id;
S.isDrawing = true;
saveSnapshot();
beginStroke();
eraseSegment(pos.x, pos.y, pos.x, pos.y);
}
function topWritableLayer() {
let hit = null;
for (const l of S.layers) {
if (l.locked || l.visible === false) continue;
if (!hit || (l.z || 0) >= (hit.z || 0)) hit = l;
}
return hit;
}
function onPenMouseDown(pos) {
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 / viewScale(), S.shapeLineWidth * 1.5)) {
S.penPath.closed = true;
S.penPath.nearStart = true;
S.penPath.preview = null;
commitPenPath();
} else {
S.penPath.pts.push(point);
renderObjects({ id: "pen-preview", type: "pen", pts: S.penPath.pts.concat(S.penPath.preview ? [S.penPath.preview] : []), closed: false, color: S.color, lw: Math.max(1, S.shapeLineWidth), fill: false, opacity: 1, visible: true });
}
return;
}
function onShapeMouseDown(pos) {
if (S.selectedShapeId) {
S.selectedShapeId = null;
renderObjects();
renderLayerPanel();
}
S.isDrawing = true;
}
var DRAW_MOVE_HANDLERS = {
brush: onBrushDrawMove,
eraser: onEraserDrawMove,
pen: onPenDrawMove,
rect: onShapeDrawMove,
arrow: onShapeDrawMove,
circle: onShapeDrawMove,
crop: onCropDrawMove
};
function onMouseMove(e) {
S._altDown = !!e.altKey;
if (S.placingImage && S.placingHandle && S.placingStart) {
onPlacementDragMove(e);
return;
}
if (S.placingImage) {
onPlacementHoverMove(e);
return;
}
if (S.panning && S.panStart) {
onPanMouseMove(e);
return;
}
const pos0 = getPos(e);
if (S.marquee) {
updateMarquee(pos0);
return;
}
if (S.lassoPts) {
updateLasso(pos0);
return;
}
if (S.bitmapDrag) {
onBitmapDragMouseMove(pos0);
return;
}
if (S.textDrag) {
onTextDragMouseMove(pos0);
return;
}
if (S.penDragPt >= 0) {
onPenEditDragMove(pos0);
return;
}
if (S.shapeDrag) {
onShapeDragMouseMove(pos0);
return;
}
if (!S.isDrawing) return;
const pos = pos0;
const handler = Object.prototype.hasOwnProperty.call(DRAW_MOVE_HANDLERS, S.tool) ? DRAW_MOVE_HANDLERS[S.tool] : null;
if (handler) handler(pos);
}
function onPlacementDragMove(e) {
const pos = getPos(e);
resizePlacement(pos);
drawPlacementPreview();
return;
}
function onPlacementHoverMove(e) {
const pos = getPos(e);
const h = hitPlacementHandle(pos);
if (h) S.drawCanvasCursor(h === "rotate" ? ROT_CURSOR : CROP_CURSORS[h] || "move");
else S.drawCanvasCursor(insidePlacementRect(pos) ? "move" : "default");
return;
}
function onPanMouseMove(e) {
setView(
S.panStart.vx + (e.clientX - S.panStart.x),
S.panStart.vy + (e.clientY - S.panStart.y)
);
return;
}
function onBitmapDragMouseMove(pos0) {
applyBitmapDrag(pos0);
renderObjects();
return;
}
function onTextDragMouseMove(pos0) {
const t = getSelectedText();
if (t) {
if (S.textDrag.mode === "move") {
const dx = pos0.x - S.textDrag.start.x;
const dy = pos0.y - S.textDrag.start.y;
let nx = clamp(S.textDrag.layer.x + dx, 0, Math.max(0, S.imgW - 4));
let ny = clamp(S.textDrag.layer.y + dy, 0, Math.max(0, S.imgH - 4));
if (!S._altDown) {
const b = textBounds(t);
const offX = b.x - t.x;
const offY = b.y - t.y;
const s = snapMove({ x: nx + offX, y: ny + offY, w: b.w, h: b.h }, otherObjectBoxes(t));
nx += s.dx;
ny += s.dy;
S.guides = s.guides.length ? s.guides : null;
} else {
S.guides = null;
}
t.x = nx;
t.y = ny;
} else if (S.textDrag.mode === "rotate") {
const st = S.textDrag;
const a1 = Math.atan2(pos0.y - st.cy, pos0.x - st.cx);
const a0 = Math.atan2(st.startY0 - st.cy, st.startX0 - st.cx);
let deg = st.rotation;
if (st.startX0 !== void 0) deg = st.rotation + (a1 - a0) * 180 / Math.PI;
if (S._shiftDown) deg = Math.round(deg / 15) * 15;
t.rotation = deg;
} else if (S.textDrag.mode === "scale") {
const dx = pos0.x - S.textDrag.anchor.x;
const dy = pos0.y - S.textDrag.anchor.y;
const d = Math.sqrt(dx * dx + dy * dy);
const f = d / Math.max(S.textDrag.d0, 1);
t.fontSize = clamp(Math.round(S.textDrag.fontSize * f), 8, 2e3);
}
renderObjects();
}
return;
}
function onPenEditDragMove(pos0) {
const penShape = getPenEditingShape();
if (penShape && penShape.pts[S.penDragPt]) {
penShape.pts[S.penDragPt].x = clamp(pos0.x, 0, S.imgW);
penShape.pts[S.penDragPt].y = clamp(pos0.y, 0, S.imgH);
renderObjects();
}
return;
}
function onShapeDragMouseMove(pos0) {
const sh = getSelectedShape();
if (sh) {
if (S.shapeDrag.mode === "move") {
const dx = pos0.x - S.shapeDrag.start.x;
const dy = pos0.y - S.shapeDrag.start.y;
const b = shapeBounds(S.shapeDrag.shape);
let cdx = clamp(dx, -b.x, Math.max(-b.x, S.imgW - (b.x + b.w)));
let cdy = clamp(dy, -b.y, Math.max(-b.y, S.imgH - (b.y + b.h)));
if (!S._altDown) {
const box = { x: b.x + cdx, y: b.y + cdy, w: b.w, h: b.h };
const s = snapMove(box, otherObjectBoxes(sh));
cdx += s.dx;
cdy += s.dy;
S.guides = s.guides.length ? s.guides : null;
} else {
S.guides = null;
}
if (sh.type === "pen") {
sh.pts = (S.shapeDrag.shape.pts || []).map((p) => ({ x: p.x + cdx, y: p.y + cdy }));
} else {
sh.x1 = S.shapeDrag.shape.x1 + cdx;
sh.y1 = S.shapeDrag.shape.y1 + cdy;
sh.x2 = S.shapeDrag.shape.x2 + cdx;
sh.y2 = S.shapeDrag.shape.y2 + cdy;
}
} else {
applyShapeHandle(sh, S.shapeDrag.handle, pos0);
}
renderObjects();
}
return;
}
function onBrushDrawMove(pos) {
strokeSegment(S.startX, S.startY, pos.x, pos.y);
S.startX = pos.x;
S.startY = pos.y;
drawToolRing(pos);
}
function onEraserDrawMove(pos) {
eraseSegment(S.startX, S.startY, pos.x, pos.y);
S.startX = pos.x;
S.startY = pos.y;
drawToolRing(pos);
}
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 / viewScale(), S.shapeLineWidth * 1.5);
S.penPath.nearStart = !!nearStart;
renderObjects();
}
}
function onShapeDrawMove(pos) {
const temp = {
id: "temp",
type: S.tool,
x1: S.startX,
y1: S.startY,
x2: pos.x,
y2: pos.y,
color: S.color,
lw: Math.max(1, S.shapeLineWidth),
lineWidth: Math.max(1, S.shapeLineWidth),
fill: S.tool === "rect" || S.tool === "circle" ? !!S.rectFill : false,
radius: S.tool === "rect" ? Math.max(0, S.shapeRadius) : 0,
opacity: 1,
visible: true
};
renderObjects(temp);
}
function onCropDrawMove(pos) {
if (S.cropHandle) {
resizeCropRect(pos);
drawCropPreview();
updateCropInfo();
} else if (S.cropMoving && S.moveStart) {
const dx = pos.x - S.moveStart.x;
const dy = pos.y - S.moveStart.y;
const r = S.moveStart.rect;
const nx = r.x + dx;
const ny = r.y + dy;
S.cropRect = { x: nx, y: ny, w: r.w, h: r.h };
drawCropPreview();
updateCropInfo();
} else {
drawCropPreview(S.startX, S.startY, pos.x, pos.y);
updateCropInfo();
}
}
var DRAW_UP_HANDLERS = {
brush: onStrokeDrawUp,
eraser: onStrokeDrawUp,
crop: onCropDrawUp,
rect: onShapeDrawUp,
arrow: onShapeDrawUp,
circle: onShapeDrawUp
};
function onMouseUp(e) {
if (S.marquee) {
endMarquee();
return;
}
if (S.lassoPts) {
endLasso();
return;
}
if (S.penDragPt >= 0) {
onPenEditMouseUp();
return;
}
if (S.placingImage && S.placingHandle) {
onPlacementMouseUp();
return;
}
if (S.panning) {
onPanMouseUp();
return;
}
if (S.textDrag) {
onTextDragMouseUp();
return;
}
if (S.bitmapDrag) {
onBitmapDragMouseUp();
return;
}
if (S.shapeDrag) {
onShapeDragMouseUp();
return;
}
if (!S.isDrawing) return;
S.isDrawing = false;
const pos = getPos(e);
const handler = Object.prototype.hasOwnProperty.call(DRAW_UP_HANDLERS, S.tool) ? DRAW_UP_HANDLERS[S.tool] : null;
if (handler) handler(pos);
}
function onPenEditMouseUp() {
const penShape = getPenEditingShape();
const pending = S.penDragPending;
S.penDragPt = -1;
S.penDragPending = null;
S.penDragBase = null;
if (pending && penShape) {
const cur = snapshotState({ metaOnly: true });
if (JSON.stringify(cur.shapes) !== JSON.stringify(pending.shapes)) {
pushHistory(S.history, pending);
S.redoStack = [];
}
}
return;
}
function onPlacementMouseUp() {
S.placingHandle = null;
S.placingStart = null;
drawPlacementPreview();
return;
}
function onPanMouseUp() {
S.panning = false;
S.panStart = null;
updateCursor();
return;
}
function onTextDragMouseUp() {
const pending = S.textDrag.pending;
if (pending) {
const cur = snapshotState({ metaOnly: true });
if (JSON.stringify(cur.texts) !== JSON.stringify(pending.texts)) {
pushHistory(S.history, pending);
S.redoStack = [];
}
}
S.textDrag = null;
S.guides = null;
renderObjects();
renderLayerPanel();
return;
}
function onBitmapDragMouseUp() {
const pending = S.bitmapDrag.pending;
if (pending) {
const cur = snapshotState({ metaOnly: true });
const before = pending.bitmaps.find((b) => b.id === S.selectedLayerId);
const after = cur.bitmaps.find((b) => b.id === S.selectedLayerId);
if (before && after && JSON.stringify([before.x, before.y, before.w, before.h]) !== JSON.stringify([after.x, after.y, after.w, after.h])) {
pushHistory(S.history, pending);
S.redoStack = [];
}
}
S.bitmapDrag = null;
S.guides = null;
renderObjects();
renderLayerPanel();
return;
}
function onShapeDragMouseUp() {
const pending = S.shapeDrag.pending;
if (pending) {
const cur = snapshotState({ metaOnly: true });
if (JSON.stringify(cur.shapes) !== JSON.stringify(pending.shapes) || JSON.stringify(cur.texts) !== JSON.stringify(pending.texts)) {
pushHistory(S.history, pending);
S.redoStack = [];
}
}
S.shapeDrag = null;
S.guides = null;
renderObjects();
renderLayerPanel();
return;
}
function onStrokeDrawUp() {
endStroke();
return;
}
function onCropDrawUp(pos) {
if (S.cropHandle) {
S.cropHandle = null;
drawCropPreview();
updateCropInfo();
return;
}
if (S.cropMoving) {
S.cropMoving = false;
S.moveStart = null;
drawCropPreview();
updateCropInfo();
return;
}
const r = applyConstraintDrag(S.startX, S.startY, pos.x, pos.y);
if (r.w > 2 && r.h > 2) {
S.cropRect = { x: r.x, y: r.y, w: r.w, h: r.h };
showCropBar();
drawCropPreview();
updateCropInfo();
} else {
clearOverlay();
}
}
function onShapeDrawUp(pos) {
const len = Math.hypot(pos.x - S.startX, pos.y - S.startY);
const ok = S.tool === "rect" || S.tool === "circle" ? Math.abs(pos.x - S.startX) > 2 && Math.abs(pos.y - S.startY) > 2 : len > 3;
if (ok) {
saveSnapshot();
const shape = {
id: "s" + Date.now() + Math.floor(Math.random() * 1e3),
type: S.tool,
x1: S.startX,
y1: S.startY,
x2: pos.x,
y2: pos.y,
color: S.color,
lw: Math.max(1, S.shapeLineWidth),
fill: S.tool === "rect" || S.tool === "circle" ? !!S.rectFill : false,
radius: S.tool === "rect" ? Math.max(0, S.shapeRadius) : 0,
opacity: 1,
visible: true,
locked: false,
z: ++S.zCounter
};
S.shapeLayers.push(shape);
renderObjects();
renderLayerPanel();
finishCreateTool("shape", shape.id);
return;
}
renderObjects();
renderLayerPanel();
}
function finishCreateTool(kind, id) {
if (["rect", "circle", "arrow", "pen"].indexOf(S.tool) < 0) return;
setTool("select");
if (!id) return;
selectUnit(kind, id);
renderObjects();
renderLayerPanel();
}
function onWheel(e) {
if (!S.open) return;
if (e.target && e.target.closest && e.target.closest(".iwb-editor-tools")) return;
e.preventDefault();
const rect = S.canvasWrap.getBoundingClientRect();
const mx = e.clientX - rect.left;
const my = e.clientY - rect.top;
const factor = e.deltaY < 0 ? ZOOM_STEP : 1 / ZOOM_STEP;
zoomStep(factor, mx, my);
}
function updateAllUI() {
updateToolUI();
updateColorUI();
updateBrushUI();
updateBrushParamUI();
updateFillUI();
updateLayerUI();
updateZoomUI();
hidePickerTip();
runtime.el.querySelectorAll(".iwb-editor-constraint-btn[data-ratio]").forEach((b) => b.classList.remove("active"));
const freeBtn = runtime.el.querySelector('.iwb-editor-constraint-btn[data-ratio="free"]');
if (freeBtn) freeBtn.classList.add("active");
hideCropBar();
updateCropInfo();
hideTextInput();
S.selectedTextId = null;
S.textDrag = null;
S.selectedShapeId = null;
S.shapeDrag = null;
renderLayerPanel();
}
function updateZoomUI() {
const val = runtime.el.querySelector(".iwb-editor-zoom-val");
if (val) val.textContent = Math.round(S.zoom * 100) + "%";
updateStatusbar();
}
function updateToolUI() {
runtime.el.querySelectorAll(".iwb-editor-tool").forEach((btn) => {
btn.classList.toggle("active", btn.dataset.tool === S.tool);
});
updateCursor();
renderOptionBar();
updateStatusbar();
}
function refreshBrushRing() {
if (!S.hoverPos) return;
if (S.tool !== "brush" && S.tool !== "eraser") return;
if (S.isDrawing) return;
drawToolRing(S.hoverPos);
}
function updateCursor() {
if (S.panning) {
S.drawCanvasCursor("grabbing");
return;
}
if (S.spaceDown) {
S.drawCanvasCursor("grab");
return;
}
if (S.tool === "hand") {
S.drawCanvasCursor("grab");
return;
}
if (S.tool === "brush" || S.tool === "eraser") {
S.drawCanvasCursor("none");
refreshBrushRing();
return;
}
if (S.tool === "crop" && S.cropRect) {
S.drawCanvasCursor("crosshair");
return;
}
S.drawCanvasCursor(S.tool === "text" ? "text" : S.tool === "select" ? "default" : "crosshair");
}
S.drawCanvasCursor = function(cur) {
for (const layer of S.layers) {
layer.canvas.style.cursor = cur;
}
};
function updateColorUI() {
let matchPreset = false;
runtime.el.querySelectorAll(".iwb-editor-color[data-color]").forEach((s) => {
const on = (s.dataset.color || "").toLowerCase() === S.color.toLowerCase();
if (on) matchPreset = true;
s.classList.toggle("active", on);
});
const panelHex = runtime.el.querySelector(".iwb-editor-color-hex");
const hexInput = runtime.el.querySelector(".iwb-editor-color-hex-input");
if (hexInput && document.activeElement !== hexInput) hexInput.value = S.color.toUpperCase();
const colorDot = runtime.el.querySelector(".iwb-editor-color-btn i");
if (colorDot) colorDot.style.background = S.color;
runtime.el.querySelectorAll(".iwb-editor-color-panel-swatch").forEach((sw) => sw.classList.toggle("active", (sw.dataset.panelColor || "").toLowerCase() === S.color.toLowerCase()));
if (panelHex) panelHex.textContent = S.color.toUpperCase();
const rgb = hexToRgb(S.color);
const max = Math.max(rgb.r, rgb.g, rgb.b) / 255, min = Math.min(rgb.r, rgb.g, rgb.b) / 255;
const d = max - min;
let h = 0;
if (d) {
if (max === rgb.r / 255) h = 60 * ((rgb.g - rgb.b) / 255 / d % 6);
else if (max === rgb.g / 255) h = 60 * ((rgb.b - rgb.r) / 255 / d + 2);
else h = 60 * ((rgb.r - rgb.g) / 255 / d + 4);
}
if (h < 0) h += 360;
const sv = runtime.el.querySelector(".iwb-color-sv"), hue = runtime.el.querySelector(".iwb-color-hue");
if (sv) sv.style.backgroundColor = `hsl(${h} 100% 50%)`;
if (hue) hue.dataset.hue = h;
const hueMarker = hue && hue.querySelector("span");
if (hueMarker) hueMarker.style.top = h / 360 * 100 + "%";
const svMarker = sv && sv.querySelector("span");
if (svMarker) {
const sat = max ? d / max : 0;
svMarker.style.left = sat * 100 + "%";
svMarker.style.top = (1 - max) * 100 + "%";
}
const custom = runtime.el.querySelector(".iwb-editor-color-custom");
if (custom) {
custom.classList.toggle("active", !matchPreset);
const inp = custom.querySelector("input");
if (inp) inp.value = S.color;
}
}
function updateBrushUI() {
syncOptionBar();
}
function updateBrushParamUI() {
syncOptionBar();
}
function updateFillUI() {
const b = runtime.el.querySelector('[data-action="toggleFill"]');
if (b) b.classList.toggle("active", !!S.rectFill);
}
function updateLayerUI() {
const hasSel = !!(S.selectedTextId || S.selectedShapeId || S.layers.some((l) => l.id === S.selectedLayerId && l.id !== "base" && !l.locked));
runtime.el.querySelectorAll(".iwb-editor-layer-btn").forEach((b) => {
b.disabled = !hasSel;
});
}
var TOOL_NAMES = {
select: "选择 / 移动",
marquee: "框选",
lasso: "套索",
brush: "画笔",
eraser: "橡皮",
pen: "钢笔",
text: "文字",
rect: "矩形",
circle: "圆形",
arrow: "箭头",
picker: "吸管",
hand: "抓手",
crop: "裁剪"
};
var OPT_HINTS = {
crop: "裁剪栏在画布下方;裁剪与选区互斥,确认后可 Ctrl+Z 撤销",
select: "点击选中元素,拖拽移动,手柄缩放",
picker: "点击画布取色;选中形状/文字时取色直接改它的颜色,取完自动切回上一个工具",
hand: "拖拽平移画布;任意工具下按住空格也可以",
marquee: "拖出选区 → 操作条就在选区旁边",
lasso: "按住拖动画圈,松手闭合"
};
function rangeOpt(key, label, min, max, value, unit) {
return `<span class="iwb-opt-label">${label}</span>
<input type="range" class="iwb-opt-range" data-opt="${key}" min="${min}" max="${max}" step="1" value="${value}">
<input type="number" class="iwb-opt-num" data-opt="${key}" min="${min}" max="${max}" step="1" value="${value}">${unit ? `<span class="iwb-opt-unit">${unit}</span>` : ""}`;
}
function presetDots(key, values) {
return `<span class="iwb-opt-dots">${values.map((v) => `<button type="button" class="iwb-opt-dot" data-opt-preset="${key}" data-value="${v}" title="${v}"><i></i></button>`).join("")}</span>`;
}
function cropOptionHTML() {
const c = S.cropConstraint;
const sizeOn = c.type === "size";
return `<span class="iwb-opt-label">比例</span>
<button type="button" class="iwb-editor-constraint-btn${c.type === "free" ? " active" : ""}" data-ratio="free">自由</button>
<button type="button" class="iwb-editor-constraint-btn" data-ratio="1:1">1:1</button>
<button type="button" class="iwb-editor-constraint-btn" data-ratio="4:3">4:3</button>
<button type="button" class="iwb-editor-constraint-btn" data-ratio="3:4">3:4</button>
<button type="button" class="iwb-editor-constraint-btn" data-ratio="16:9">16:9</button>
<button type="button" class="iwb-editor-constraint-btn" data-ratio="9:16">9:16</button>
<span class="iwb-opt-label">尺寸</span>
<input type="number" class="iwb-editor-size-input iwb-editor-size-w" min="1" placeholder="宽" value="800">
<span class="iwb-opt-unit">×</span>
<input type="number" class="iwb-editor-size-input iwb-editor-size-h" min="1" placeholder="高" value="800">
<button type="button" class="iwb-editor-constraint-btn iwb-editor-size-toggle" data-action="toggleSizeConstraint" aria-pressed="${sizeOn}">启用尺寸</button>
<button type="button" class="iwb-editor-constraint-btn iwb-editor-size-apply" data-action="applySize">应用</button>
<span class="iwb-editor-crop-info">--</span>
<button type="button" class="iwb-editor-crop-confirm" data-action="confirmCrop" title="Enter">✓ 确认</button>
<button type="button" class="iwb-editor-crop-cancel" data-action="cancelCrop" title="Esc">✗ 取消</button>
<span class="iwb-opt-hint">拖出裁剪框;Enter 确认 · Esc 取消;裁剪后可 Ctrl+Z</span>`;
}
function fillStyleHTML(owner) {
const fill = owner === "pen" ? S.penFill : S.rectFill;
return `<span class="iwb-opt-label">样式</span>
<button class="iwb-opt-btn${fill ? "" : " active"}" data-opt-toggle="stroke" data-fill-owner="${owner}" data-value="stroke" title="描边 (Shift+X 切换)">描边</button>
<button class="iwb-opt-btn${fill ? " active" : ""}" data-opt-toggle="fill" data-fill-owner="${owner}" data-value="fill" title="实心 (Shift+X 切换)">实心</button>`;
}
var SHAPE_NAMES = { rect: "矩形", circle: "圆形", arrow: "箭头", pen: "钢笔路径" };
var TEXT_STYLE_STATE_KEY = {
fontWeight: "textWeight",
align: "textAlign",
lineHeight: "textLineHeight",
strokeWidth: "textStrokeWidth",
strokeColor: "textStrokeColor",
bgFill: "textBgFill",
bgColor: "textBgColor"
};
function textStyleValues(t) {
const pick = (objKey, stateKey, dflt) => {
const raw = t ? t[objKey] : S[stateKey];
return raw == null ? dflt : raw;
};
return {
fontWeight: String(pick("fontWeight", "textWeight", "bold")),
align: pick("align", "textAlign", "left"),
lineHeight: Number(pick("lineHeight", "textLineHeight", 1.25)) || 1.25,
strokeWidth: Math.max(0, Number(pick("strokeWidth", "textStrokeWidth", 0)) || 0),
strokeColor: pick("strokeColor", "textStrokeColor", "#ffffff"),
bgFill: !!pick("bgFill", "textBgFill", false),
bgColor: pick("bgColor", "textBgColor", "#000000")
};
}
function textStyleHTML(t) {
const v = textStyleValues(t);
const wBtn = (val, label, title) => `<button class="iwb-opt-btn${v.fontWeight === val ? " active" : ""}" data-opt-text="fontWeight" data-value="${val}" title="${title}">${label}</button>`;
const aBtn = (val, label, title) => `<button class="iwb-opt-btn${v.align === val ? " active" : ""}" data-opt-text="align" data-value="${val}" title="${title}">${label}</button>`;
return `<span class="iwb-opt-sep"></span>
<span class="iwb-opt-label">字重</span>${wBtn("normal", "常规", "常规字重")}${wBtn("bold", "粗", "粗体(默认)")}${wBtn("900", "特粗", "特粗,封面标题用")}
<span class="iwb-opt-label">对齐</span>${aBtn("left", "左", "多行时按左缘对齐")}${aBtn("center", "中", "多行时居中")}${aBtn("right", "右", "多行时按右缘对齐")}
<span class="iwb-opt-label">行距</span>
<input type="number" class="iwb-opt-num" data-opt="textLineHeight" min="80" max="300" step="5" value="${Math.round(v.lineHeight * 100)}"><span class="iwb-opt-unit">%</span>
<span class="iwb-opt-sep"></span>
<span class="iwb-opt-label">描边</span>
<input type="number" class="iwb-opt-num" data-opt="textStrokeWidth" min="0" max="40" step="1" value="${Math.round(v.strokeWidth)}"><span class="iwb-opt-unit">px</span>
<input type="color" class="iwb-opt-color" data-opt-color="strokeColor" value="${v.strokeColor}" title="描边颜色">
<button class="iwb-opt-btn${v.bgFill ? " active" : ""}" data-opt-text="bgFill" data-value="${v.bgFill ? "0" : "1"}" title="给文字加一块半透明底色,压在花背景上也能看清">底色</button>
<input type="color" class="iwb-opt-color" data-opt-color="bgColor" value="${v.bgColor}" title="底色颜色;选色会自动开启底色,不用先点左侧按钮">`;
}
var SELCMD_SVGS = {
all: '<svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" stroke-dasharray="3 2"><rect x="3.5" y="3.5" width="17" height="17" rx="1"/></svg>',
invert: '<svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><rect x="3.5" y="3.5" width="17" height="17" rx="1" stroke-dasharray="3 2"/><rect x="8" y="8" width="8" height="8" rx="1" fill="currentColor" stroke="none"/></svg>',
none: '<svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><rect x="3.5" y="3.5" width="17" height="17" rx="1" stroke-dasharray="3 2"/><line x1="4" y1="20" x2="20" y2="4"/></svg>'
};
var selCmdHTML = () => `<span class="iwb-opt-sep"></span>
<button class="iwb-opt-selcmd" data-more="sel.all" title="全选 (Ctrl+A)">${SELCMD_SVGS.all}</button>
<button class="iwb-opt-selcmd" data-more="sel.invert" title="反选 (Ctrl+Shift+I)">${SELCMD_SVGS.invert}</button>
<button class="iwb-opt-selcmd" data-more="sel.none" title="取消选区 (Esc / Ctrl+D)">${SELCMD_SVGS.none}</button>`;
function selectOptionHTML() {
const sh = getSelectedShape();
if (sh) {
const t = sh.type;
if (t === "rect" || t === "circle" || t === "pen" || t === "arrow") {
const owner = t === "pen" ? "pen" : "rect";
const lw = Math.max(1, Math.round(sh.lw || S.shapeLineWidth));
return `<span class="iwb-opt-current">已选中:${SHAPE_NAMES[t] || t}</span>` + rangeOpt("shapeLineWidth", "线宽", 1, 60, lw, "") + presetDots("shapeLineWidth", [1, 2, 3, 6, 10, 16, 24]) + (t === "rect" ? rangeOpt("shapeRadius", "圆角", 0, 200, Math.round(sh.radius || 0), "px") : "") + (t === "arrow" ? "" : fillStyleHTML(owner)) + (t === "pen" && !sh.closed ? '<span class="iwb-opt-hint">这条钢笔路径未闭合,实心不生效;点回起点闭合后即可填充</span>' : "") + selCmdHTML();
}
}
const text = getSelectedText();
if (text) {
return `<span class="iwb-opt-current">已选中:文字</span>` + rangeOpt("textSize", "字号", 8, 400, Math.round(text.fontSize || S.textSize), "px") + textStyleHTML(text) + selCmdHTML() + '<span class="iwb-opt-hint">双击改内容 · 拖动手柄缩放</span>';
}
return `<span class="iwb-opt-current">当前工具:选择 / 移动</span>` + selCmdHTML() + '<span class="iwb-opt-hint">点中矩形/圆形/钢笔/文字后,这里出现它的描边、实心与粗细</span>';
}
function optionBarHTML(tool) {
if (tool === "crop") return cropOptionHTML();
if (tool === "select") return selectOptionHTML();
if (tool === "brush" || tool === "eraser") {
return rangeOpt("brushSize", "大小", 1, 300, S.brushSize, "") + presetDots("brushSize", [2, 4, 8, 12]) + `<span class="iwb-opt-label">硬度</span>
<input type="range" class="iwb-opt-range iwb-opt-range-wide" data-opt="brushHardness" min="0" max="100" step="1" value="${S.brushHardness}">
<span class="iwb-opt-val" data-opt-val="brushHardness">${S.brushHardness}</span>
<span class="iwb-opt-label">透明</span>
<input type="range" class="iwb-opt-range" data-opt="brushOpacity" min="5" max="100" step="1" value="${Math.round(S.brushOpacity * 100)}">
<span class="iwb-opt-val" data-opt-val="brushOpacity">${Math.round(S.brushOpacity * 100)}%</span>` + presetDots("brushHardness", [0, 25, 50, 75, 100]);
}
if (tool === "rect" || tool === "circle") {
return rangeOpt("shapeLineWidth", "线宽", 1, 60, S.shapeLineWidth, "") + presetDots("shapeLineWidth", [1, 2, 3, 6, 10, 16, 24]) + (tool === "rect" ? rangeOpt("shapeRadius", "圆角", 0, 200, S.shapeRadius, "px") : "") + fillStyleHTML("rect");
}
if (tool === "arrow") {
return rangeOpt("shapeLineWidth", "线宽", 1, 60, S.shapeLineWidth, "") + presetDots("shapeLineWidth", [1, 2, 3, 6, 10, 16, 24]) + '<span class="iwb-opt-hint">拖出箭头,松手完成</span>';
}
if (tool === "pen") {
return rangeOpt("shapeLineWidth", "线宽", 1, 60, S.shapeLineWidth, "") + presetDots("shapeLineWidth", [1, 2, 3, 6, 10, 16, 24]) + fillStyleHTML("pen") + '<span class="iwb-opt-hint">逐点点击,点回起点闭合;闭合后可切换描边/实心</span>';
}
if (tool === "text") {
return rangeOpt("textSize", "字号", 8, 400, S.textSize, "px") + textStyleHTML(null) + '<span class="iwb-opt-hint">点画布输入文字,Enter 确认,Shift+Enter 换行</span>';
}
if (tool === "marquee") {
return `<span class="iwb-opt-label">形状</span>
<button class="iwb-opt-btn${S.selectionKind === "rect" ? " active" : ""}" data-opt="shape" data-value="rect">矩形</button>
<button class="iwb-opt-btn${S.selectionKind === "ellipse" ? " active" : ""}" data-opt="shape" data-value="ellipse">椭圆</button>
<label class="iwb-opt-label">羽化 <input type="number" class="iwb-opt-num" data-opt="feather" min="0" max="20" step="1" value="${S.selectionFeather}"> px</label>
<span class="iwb-opt-hint">${OPT_HINTS.marquee}</span>`;
}
if (tool === "lasso") {
return `<span class="iwb-opt-label">羽化 <input type="number" class="iwb-opt-num" data-opt="feather" min="0" max="20" step="1" value="${S.selectionFeather}"> px</span>
<span class="iwb-opt-hint">${OPT_HINTS.lasso}</span>`;
}
return `<span class="iwb-opt-current">当前工具:${TOOL_NAMES[tool] || tool}</span>
<span class="iwb-opt-hint">${OPT_HINTS[tool] || "选区工具按 M / L;Ctrl+J 复制选区,Delete 清除当前层"}</span>`;
}
function renderOptionBar(force) {
const body = runtime.el && runtime.el.querySelector(".iwb-editor-optionbar-body");
if (!body) return;
const sig = S.tool + "|" + (S.selectedShapeId || "") + "|" + (S.selectedTextId || "");
if (!force && body.dataset.sig === sig) {
syncOptionBar();
return;
}
body.dataset.sig = sig;
body.dataset.tool = S.tool;
body.innerHTML = optionBarHTML(S.tool);
if (S.tool === "crop") updateCropInfo();
syncOptionBar();
}
function syncOptionBar() {
const body = runtime.el && runtime.el.querySelector(".iwb-editor-optionbar-body");
if (!body) return;
const selShape = S.tool === "select" ? getSelectedShape() : null;
const selText = S.tool === "select" ? getSelectedText() : null;
const val = (key) => {
if (key === "brushSize") return S.brushSize;
if (key === "brushHardness") return S.brushHardness;
if (key === "brushOpacity") return Math.round(S.brushOpacity * 100);
if (key === "shapeLineWidth") return selShape ? Math.max(1, Math.round(selShape.lw || S.shapeLineWidth)) : S.shapeLineWidth;
if (key === "shapeRadius") return selShape && selShape.type === "rect" ? Math.round(selShape.radius || 0) : S.shapeRadius;
if (key === "textSize") return selText ? Math.round(selText.fontSize || S.textSize) : S.textSize;
if (key === "textLineHeight") return Math.round((selText ? Number(selText.lineHeight) || S.textLineHeight : S.textLineHeight) * 100);
if (key === "textStrokeWidth") return Math.round(selText ? Number(selText.strokeWidth) || 0 : S.textStrokeWidth);
if (key === "feather") return S.selectionFeather;
return "";
};
body.querySelectorAll("input[data-opt]").forEach((el) => {
if (document.activeElement === el) return;
const v = val(el.dataset.opt);
if (String(el.value) !== String(v)) el.value = v;
});
body.querySelectorAll("[data-opt-val]").forEach((el) => {
const v = val(el.dataset.optVal);
el.textContent = el.dataset.optVal === "brushOpacity" ? v + "%" : v;
});
body.querySelectorAll('[data-opt="shape"]').forEach((btn) => {
btn.classList.toggle("active", S.selectionKind === btn.dataset.value);
});
body.querySelectorAll("[data-opt-toggle]").forEach((btn) => {
const owner = btn.dataset.fillOwner === "pen" ? "pen" : "rect";
let cur = owner === "pen" ? S.penFill : S.rectFill;
if (selShape && (owner === "pen" ? selShape.type === "pen" : selShape.type === "rect" || selShape.type === "circle")) {
cur = !!selShape.fill;
}
btn.classList.toggle("active", !!cur === (btn.dataset.value === "fill"));
});
const sv = textStyleValues(selText);
body.querySelectorAll("[data-opt-text]").forEach((btn) => {
const k = btn.dataset.optText;
if (k === "bgFill") {
btn.classList.toggle("active", !!sv.bgFill);
btn.dataset.value = sv.bgFill ? "0" : "1";
return;
}
btn.classList.toggle("active", String(sv[k]) === btn.dataset.value);
});
body.querySelectorAll("[data-opt-color]").forEach((inp) => {
if (document.activeElement === inp) return;
const v = sv[inp.dataset.optColor];
if (v && String(inp.value).toLowerCase() !== String(v).toLowerCase()) inp.value = v;
});
}
function updateStatusbar() {
if (!runtime.el) return;
const put = (sel2, text) => {
const el = runtime.el.querySelector(sel2);
if (el && el.textContent !== text) el.textContent = text;
};
put(".iwb-editor-status-zoom", Math.round(S.zoom * 100) + "%");
put(".iwb-editor-status-size", S.imgW + "×" + S.imgH);
const p = S.lastPos;
put(".iwb-editor-status-pos", p ? "x " + Math.round(p.x) + " y " + Math.round(p.y) : "x — y —");
const sel = S.selection && S.selection.active ? S.selection : null;
put(".iwb-editor-status-sel", sel ? "选区 " + Math.round(sel.bbox.w) + "×" + Math.round(sel.bbox.h) + (sel.feather ? " · 羽化 " + sel.feather : "") + (sel.inverted ? " · 反选" : "") : "无选区");
const layer = S.layers.find((l) => l.id === S.activeLayerId);
put(".iwb-editor-status-layer", "当前层:" + (layer ? layer.name : "—"));
put(".iwb-editor-status-tool", TOOL_NAMES[S.tool] || S.tool);
}
var lwSnapDone = false;
var textSnapDone = false;
function applyShapeLineWidth(committed) {
const sh = getSelectedShape();
if (!sh || sh.locked) {
lwSnapDone = false;
return;
}
if (committed || !lwSnapDone) {
saveSnapshot("线宽");
lwSnapDone = true;
}
sh.lw = S.shapeLineWidth;
renderObjects();
if (committed) lwSnapDone = false;
}
function applyTextSize(committed) {
const t = getSelectedText();
if (!t || t.locked) {
textSnapDone = false;
return;
}
if (committed || !textSnapDone) {
saveSnapshot("字号");
textSnapDone = true;
}
t.fontSize = S.textSize;
renderObjects();
if (committed) textSnapDone = false;
}
var textStyleSnapDone = false;
function applyTextStyle(key, raw, committed) {
const stateKey = TEXT_STYLE_STATE_KEY[key];
if (!stateKey) return;
let value = raw;
if (key === "bgFill") value = raw === true || raw === 1 || raw === "1" || raw === "true";
else if (key === "lineHeight") value = clamp(Number(raw) || 125, 80, 300) / 100;
else if (key === "strokeWidth") value = clamp(Number(raw) || 0, 0, 40);
else if (key === "strokeColor" || key === "bgColor") value = String(raw || "#000000").toLowerCase();
else value = String(raw);
S[stateKey] = value;
const t = getSelectedText();
if (!t || t.locked) {
textStyleSnapDone = false;
return;
}
if (committed || !textStyleSnapDone) {
saveSnapshot("文字样式");
textStyleSnapDone = true;
}
t[key] = value;
if (key === "bgColor" && !t.bgFill) {
t.bgFill = true;
S.textBgFill = true;
}
renderObjects();
if (key === "bgColor") syncOptionBar();
if (committed) textStyleSnapDone = false;
}
var radiusSnapDone = false;
function applyShapeRadius(committed) {
const sh = getSelectedShape();
if (!sh || sh.locked || sh.type !== "rect") {
radiusSnapDone = false;
return;
}
if (committed || !radiusSnapDone) {
saveSnapshot("圆角");
radiusSnapDone = true;
}
sh.radius = S.shapeRadius;
renderObjects();
if (committed) radiusSnapDone = false;
}
function setShapeFill(fill, owner) {
const isPen = owner === "pen";
if (isPen) S.penFill = !!fill;
else S.rectFill = !!fill;
updateFillUI();
syncOptionBar();
const sh = getSelectedShape();
const types = isPen ? ["pen"] : ["rect", "circle"];
if (sh && types.indexOf(sh.type) >= 0 && !sh.locked) {
saveSnapshot("填充");
sh.fill = isPen ? !!S.penFill && !!sh.closed : !!S.rectFill;
renderObjects();
syncOptionBar();
}
}
function setOptionFromControl(el, committed) {
const key = el && el.dataset ? el.dataset.opt : "";
if (!key) return;
const n = Math.round(Number(el.value));
const safe = Number.isFinite(n) ? n : 0;
if (key === "brushSize") {
S.brushSize = clamp(safe || 1, 1, 300);
updateBrushUI();
updateBrushParamUI();
refreshBrushRing();
} else if (key === "brushHardness") {
S.brushHardness = clamp(safe, 0, 100);
updateBrushParamUI();
} else if (key === "brushOpacity") {
S.brushOpacity = clamp(safe || 100, 5, 100) / 100;
updateBrushParamUI();
if (S.strokeCanvas) S.strokeCanvas.style.opacity = S.brushOpacity;
} else if (key === "shapeLineWidth") {
S.shapeLineWidth = clamp(safe || 1, 1, 60);
applyShapeLineWidth(committed);
} else if (key === "textSize") {
S.textSize = clamp(safe || 32, 8, 400);
applyTextSize(committed);
} else if (key === "textLineHeight") {
applyTextStyle("lineHeight", safe || 125, committed);
} else if (key === "textStrokeWidth") {
applyTextStyle("strokeWidth", safe, committed);
} else if (key === "shapeRadius") {
S.shapeRadius = clamp(safe, 0, 400);
applyShapeRadius(committed);
} else if (key === "feather") {
S.selectionFeather = clamp(safe, 0, 20);
if (S.selection && S.selection.active) S.selection.feather = S.selectionFeather;
updateStatusbar();
}
syncOptionBar();
}
function togglePanelsCollapsed() {
const root = runtime.el;
if (!root) return;
const collapsed = !root.classList.contains("panels-collapsed");
root.classList.toggle("panels-collapsed", collapsed);
const st = S.callbacks && S.callbacks.settings;
if (st && typeof st.set === "function") {
try {
st.set("panelsCollapsed", collapsed);
} catch (err) {
}
}
toast(collapsed ? "侧栏已收起" : "侧栏已展开", "info");
}
function bindLiteUI() {
const root = runtime.el;
if (!root || root.dataset.liteBound === "1") return;
root.dataset.liteBound = "1";
const closeMenus = () => {
const panel = root.querySelector(".iwb-editor-export-settings");
if (panel) panel.classList.remove("open");
const toggle = root.querySelector('[data-action="toggleExportSettings"]');
if (toggle) toggle.setAttribute("aria-expanded", "false");
};
root.addEventListener("click", (e) => {
const fxBtn = e.target.closest("[data-fx]");
if (fxBtn) {
e.stopPropagation();
applyQuickEffect(fxBtn.dataset.fx);
return;
}
const btn = e.target.closest("[data-more]");
if (!btn) return;
e.stopPropagation();
const key = btn.dataset.more;
if (key && key.indexOf("sel.") === 0) runCommand(key);
else if (key === "addBlankLayer") addBlankLayer();
else if (key === "zoomFit") setZoomFit();
else if (key === "reset") restoreAll();
});
root.querySelectorAll('[data-action="togglePanels"]').forEach((btn) => {
btn.addEventListener("mousedown", (e) => e.stopPropagation());
btn.addEventListener("click", (e) => {
e.stopPropagation();
togglePanelsCollapsed();
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());
body.addEventListener("input", (e) => setOptionFromControl(e.target, false));
body.addEventListener("change", (e) => {
const colorEl = e.target.closest ? e.target.closest("[data-opt-color]") : null;
if (colorEl) {
e.stopPropagation();
applyTextStyle(colorEl.dataset.optColor, colorEl.value, true);
syncOptionBar();
return;
}
setOptionFromControl(e.target, true);
});
body.addEventListener("click", (e) => {
const textBtn = e.target.closest("[data-opt-text]");
if (textBtn) {
e.stopPropagation();
const k = textBtn.dataset.optText;
applyTextStyle(k, textBtn.dataset.value, true);
syncOptionBar();
return;
}
const shapeBtn = e.target.closest('[data-opt="shape"]');
if (shapeBtn) {
e.stopPropagation();
S.selectionKind = shapeBtn.dataset.value === "ellipse" ? "ellipse" : "rect";
syncOptionBar();
toast("选区形状:" + (S.selectionKind === "ellipse" ? "椭圆" : "矩形"), "info");
return;
}
const toggle = e.target.closest("[data-opt-toggle]");
if (toggle) {
e.stopPropagation();
setShapeFill(toggle.dataset.value === "fill", toggle.dataset.fillOwner);
return;
}
const dot = e.target.closest("[data-opt-preset]");
if (dot) {
e.stopPropagation();
setOptionFromControl({ dataset: { opt: dot.dataset.optPreset }, value: dot.dataset.value }, true);
return;
}
const ratioBtn = e.target.closest("[data-ratio]");
if (ratioBtn) {
e.stopPropagation();
const ratio = parseRatio(ratioBtn.dataset.ratio);
body.querySelectorAll(".iwb-editor-constraint-btn[data-ratio]").forEach((b) => b.classList.toggle("active", b === ratioBtn));
setConstraint(ratio > 0 ? "ratio" : "free", ratio > 0 ? ratio : 0, 0, 0);
return;
}
if (e.target.closest('[data-action="toggleSizeConstraint"]')) {
e.stopPropagation();
if (S.cropConstraint.type === "size") {
setConstraint("free", 0, 0, 0);
} else {
const w = parseInt(body.querySelector(".iwb-editor-size-w").value, 10);
const h = parseInt(body.querySelector(".iwb-editor-size-h").value, 10);
if (w > 0 && h > 0) {
body.querySelectorAll(".iwb-editor-constraint-btn[data-ratio]").forEach((b) => b.classList.remove("active"));
setConstraint("size", w / h, w, h);
}
}
return;
}
if (e.target.closest('[data-action="applySize"]')) {
e.stopPropagation();
const w = parseInt(body.querySelector(".iwb-editor-size-w").value, 10);
const h = parseInt(body.querySelector(".iwb-editor-size-h").value, 10);
if (w > 0 && h > 0) {
body.querySelectorAll(".iwb-editor-constraint-btn[data-ratio]").forEach((b) => b.classList.remove("active"));
setConstraint("size", w / h, w, h);
}
return;
}
if (e.target.closest('[data-action="confirmCrop"]')) {
e.stopPropagation();
confirmCrop();
return;
}
if (e.target.closest('[data-action="cancelCrop"]')) {
e.stopPropagation();
cancelCrop();
return;
}
});
}
const modal = root.querySelector(".iwb-editor-modal") || root;
modal.addEventListener("mousedown", (e) => {
if (!e.target.closest(".iwb-editor-export-settings-wrap")) closeMenus();
}, true);
}
var warnedMissing = /* @__PURE__ */ new Set();
function bindIf(selector, type, handler, root) {
const el = (root || runtime.el).querySelector(selector);
if (!el) {
if (!warnedMissing.has(selector)) {
warnedMissing.add(selector);
console.warn("[IWB编辑器] 未找到元素,跳过绑定:" + selector);
}
return null;
}
el.addEventListener(type, handler);
return el;
}
function bindAll(selector, type, handler) {
const list = runtime.el.querySelectorAll(selector);
list.forEach((el) => el.addEventListener(type, handler));
return list.length;
}
function bindEvents() {
bindToolButtons();
bindColorPanel();
bindColorPalette();
bindFillToggle();
bindLayerOrderButtons();
bindZoomButtons();
bindHistoryActions();
bindLayerAddActions();
bindExportActions();
bindWheelZoom();
bindTextInput();
bindGlobalListeners();
}
function bindToolButtons() {
runtime.el.querySelectorAll(".iwb-editor-tool").forEach((btn) => {
if (!btn.dataset.tool) return;
btn.addEventListener("mousedown", (e) => e.stopPropagation());
btn.addEventListener("click", () => setTool(btn.dataset.tool));
});
}
function closeColorPop() {
const pop = runtime.el && runtime.el.querySelector(".iwb-editor-color-pop");
if (!pop || pop.hidden) return false;
pop.hidden = true;
const btn = runtime.el.querySelector('[data-action="toggleColorPop"]');
if (btn) {
btn.classList.remove("active");
btn.setAttribute("aria-expanded", "false");
}
return true;
}
function positionColorPop() {
const pop = runtime.el && runtime.el.querySelector(".iwb-editor-color-pop");
const btn = runtime.el && runtime.el.querySelector('[data-action="toggleColorPop"]');
const modal = runtime.el && runtime.el.querySelector(".iwb-editor-modal");
if (!pop || !btn || !modal || pop.hidden) return;
const mr = modal.getBoundingClientRect();
const br = btn.getBoundingClientRect();
const pr = pop.getBoundingClientRect();
let left = br.left - mr.left - 10;
left = Math.min(Math.max(8, left), Math.max(8, mr.width - pr.width - 8));
let top = br.top - mr.top - pr.height - 10;
if (top < 8) top = br.bottom - mr.top + 10;
pop.style.left = Math.round(left) + "px";
pop.style.top = Math.round(top) + "px";
}
function toggleColorPop() {
const pop = runtime.el.querySelector(".iwb-editor-color-pop");
const btn = runtime.el.querySelector('[data-action="toggleColorPop"]');
if (!pop || !btn) return;
if (pop.hidden) {
pop.hidden = false;
btn.classList.add("active");
btn.setAttribute("aria-expanded", "true");
positionColorPop();
} else {
closeColorPop();
}
}
function bindColorPanel() {
const pop = runtime.el.querySelector(".iwb-editor-color-pop");
const colorBtn = runtime.el.querySelector('[data-action="toggleColorPop"]');
if (colorBtn) {
colorBtn.addEventListener("mousedown", (e) => e.stopPropagation());
colorBtn.addEventListener("click", (e) => {
e.stopPropagation();
toggleColorPop();
});
}
if (pop) {
pop.addEventListener("mousedown", (e) => e.stopPropagation());
document.addEventListener("mousedown", (e) => {
if (!pop.hidden && !pop.contains(e.target) && !(colorBtn && colorBtn.contains(e.target))) closeColorPop();
}, true);
window.addEventListener("resize", positionColorPop);
}
const setPanelColor = (color) => applyColorChange(color);
let dragSnapped = false;
const hasColorTarget = () => {
const t = getSelectedText(), sh = getSelectedShape();
return !!(t && !t.locked || sh && !sh.locked);
};
const setDragColor = (color) => {
if (!dragSnapped) {
if (hasColorTarget()) {
saveSnapshot();
dragSnapped = true;
}
}
applyColorChange(color, { skipHistory: true });
};
const panelHexInput = runtime.el.querySelector(".iwb-editor-color-hex-input");
if (panelHexInput) panelHexInput.addEventListener("change", () => {
if (/^#[0-9a-f]{6}$/i.test(panelHexInput.value)) setPanelColor(panelHexInput.value);
});
if (pop) {
pop.addEventListener("click", (e) => {
const btn = e.target.closest("[data-panel-color]");
if (!btn) return;
e.stopPropagation();
setPanelColor(btn.dataset.panelColor);
});
}
const palettePick = runtime.el.querySelector('[data-action="palettePick"]');
if (palettePick) {
palettePick.addEventListener("mousedown", (e) => e.stopPropagation());
palettePick.addEventListener("click", () => {
closeColorPop();
setTool("picker");
});
}
const sv = runtime.el.querySelector(".iwb-color-sv");
const hue = runtime.el.querySelector(".iwb-color-hue");
const initHsv = (() => {
const { r, g, b } = hexToRgb(S.color);
const rr = r / 255, gg = g / 255, bb = b / 255;
const max = Math.max(rr, gg, bb), min = Math.min(rr, gg, bb), d = max - min;
let h = 0;
if (d) {
if (max === rr) h = 60 * ((gg - bb) / d % 6);
else if (max === gg) h = 60 * ((bb - rr) / d + 2);
else h = 60 * ((rr - gg) / d + 4);
}
if (h < 0) h += 360;
return { h, sat: max ? d / max : 0, val: max };
})();
let hueValue = initHsv.h;
let satValue = initHsv.sat;
let valValue = initHsv.val;
const hsvToHex = (h, sat, val) => {
const c = val * sat, x = c * (1 - Math.abs(h / 60 % 2 - 1)), m = val - c;
let r = 0, g = 0, b = 0;
if (h < 60) {
r = c;
g = x;
} else if (h < 120) {
r = x;
g = c;
} else if (h < 180) {
g = c;
b = x;
} else if (h < 240) {
g = x;
b = c;
} else if (h < 300) {
r = x;
b = c;
} else {
r = c;
b = x;
}
return rgbToHex(Math.round((r + m) * 255), Math.round((g + m) * 255), Math.round((b + m) * 255));
};
const pick = (target, e) => {
const r = target.getBoundingClientRect();
const x = clamp((e.clientX - r.left) / r.width, 0, 1);
const y = clamp((e.clientY - r.top) / r.height, 0, 1);
if (target === hue) hueValue = y * 360;
else {
satValue = x;
valValue = 1 - y;
}
setDragColor(hsvToHex(hueValue, satValue, valValue));
};
const syncFromColor = () => {
const { r, g, b } = hexToRgb(S.color);
const rr = r / 255, gg = g / 255, bb = b / 255;
const max = Math.max(rr, gg, bb), min = Math.min(rr, gg, bb), d = max - min;
if (d > 0) {
let h = 0;
if (max === rr) h = 60 * ((gg - bb) / d % 6);
else if (max === gg) h = 60 * ((bb - rr) / d + 2);
else h = 60 * ((rr - gg) / d + 4);
if (h < 0) h += 360;
hueValue = h;
}
satValue = max ? d / max : 0;
valValue = max;
};
const beginDrag = (target, e) => {
syncFromColor();
dragSnapped = false;
pick(target, e);
};
if (sv) {
sv.addEventListener("pointerdown", (e) => {
sv.setPointerCapture(e.pointerId);
beginDrag(sv, e);
});
sv.addEventListener("pointermove", (e) => {
if (e.buttons) pick(sv, e);
});
}
if (hue) {
hue.addEventListener("pointerdown", (e) => {
beginDrag(hue, e);
});
hue.addEventListener("pointermove", (e) => {
if (e.buttons) pick(hue, e);
});
}
}
function bindColorPalette() {
runtime.el.querySelectorAll(".iwb-editor-color[data-color]").forEach((s) => {
s.addEventListener("mousedown", (e) => e.stopPropagation());
s.addEventListener("click", () => applyColorChange(s.dataset.color));
});
const colorInput = runtime.el.querySelector(".iwb-editor-color-picker-input");
if (colorInput) {
colorInput.addEventListener("mousedown", (e) => e.stopPropagation());
colorInput.addEventListener("input", () => applyColorChange(colorInput.value));
}
}
function bindFillToggle() {
const fillBtn = runtime.el.querySelector('[data-action="toggleFill"]');
if (fillBtn) fillBtn.addEventListener("mousedown", (e) => e.stopPropagation());
fillBtn && fillBtn.addEventListener("click", () => {
S.rectFill = !S.rectFill;
updateFillUI();
const sh = getSelectedShape();
if (sh && (sh.type === "rect" || sh.type === "circle") && (S.tool === "rect" || S.tool === "circle" || S.tool === "select")) {
saveSnapshot();
sh.fill = S.rectFill;
renderObjects();
}
});
}
function bindLayerOrderButtons() {
runtime.el.querySelectorAll(".iwb-editor-layer-btn").forEach((btn) => {
btn.addEventListener("mousedown", (e) => e.stopPropagation());
btn.addEventListener("click", () => moveLayer(btn.dataset.layer));
});
}
function bindZoomButtons() {
bindIf('[data-action="zoomOut"]', "click", (e) => {
e.stopPropagation();
zoomStep(1 / ZOOM_STEP, S.canvasWrap.clientWidth / 2, S.canvasWrap.clientHeight / 2);
});
bindIf('[data-action="zoomIn"]', "click", (e) => {
e.stopPropagation();
zoomStep(ZOOM_STEP, S.canvasWrap.clientWidth / 2, S.canvasWrap.clientHeight / 2);
});
bindAll('[data-action="zoomFit"]', "click", (e) => {
e.stopPropagation();
setZoomFit();
});
}
function bindHistoryActions() {
const undoBtn = runtime.el.querySelector('[data-action="undo"]');
const redoBtn = runtime.el.querySelector('[data-action="redo"]');
const resetBtn = runtime.el.querySelector('[data-action="reset"]');
const restoreBtn = runtime.el.querySelector('[data-action="restore"]');
undoBtn && undoBtn.addEventListener("mousedown", (e) => e.stopPropagation());
redoBtn && redoBtn.addEventListener("mousedown", (e) => e.stopPropagation());
resetBtn && resetBtn.addEventListener("mousedown", (e) => e.stopPropagation());
restoreBtn && restoreBtn.addEventListener("mousedown", (e) => e.stopPropagation());
undoBtn && undoBtn.addEventListener("click", undo);
redoBtn && redoBtn.addEventListener("click", redo);
resetBtn && resetBtn.addEventListener("click", resetDraw);
restoreBtn && restoreBtn.addEventListener("click", restoreOriginal);
}
function bindLayerAddActions() {
bindAll('[data-action="addBitmapLayer"]', "mousedown", (e) => e.stopPropagation());
bindAll('[data-action="addBitmapLayer"]', "click", () => {
const fileInput = document.createElement("input");
fileInput.type = "file";
fileInput.accept = "image/*";
fileInput.addEventListener("change", async () => {
const file = fileInput.files[0];
if (!file) return;
const reader = new FileReader();
reader.onload = async () => {
try {
const img = await loadImage(reader.result);
addBitmapLayer(img);
} catch (err) {
console.error("[IWB编辑器] 导入图层失败:", err);
}
};
reader.readAsDataURL(file);
});
fileInput.click();
});
bindAll('[data-action="addBlankLayer"]', "mousedown", (e) => e.stopPropagation());
bindAll('[data-action="addBlankLayer"]', "click", () => {
addBlankLayer();
});
bindAll('[data-action="mergeLayers"]', "mousedown", (e) => e.stopPropagation());
bindAll('[data-action="mergeLayers"]', "click", () => {
const r = mergeLayers();
toast(r.msg, r.ok ? "success" : "warn");
});
bindAll('[data-action="mergeVisible"]', "mousedown", (e) => e.stopPropagation());
bindAll('[data-action="mergeVisible"]', "click", () => {
const r = mergeVisibleLayers();
toast(r.msg, r.ok ? "success" : "warn");
});
}
function bindExportActions() {
bindIf('[data-action="cancel"]', "click", close);
bindIf('[data-action="download"]', "click", () => exportResult("download"));
bindIf('[data-action="copyClipboard"]', "click", () => copyResult());
bindIf('[data-action="newNode"]', "click", () => exportResult("newNode"));
bindIf('[data-action="replace"]', "click", () => exportResult("replace"));
}
function bindWheelZoom() {
S.canvasWrap.addEventListener("wheel", onWheel, { passive: false });
}
function bindTextInput() {
const textInput = runtime.el.querySelector(".iwb-editor-text-input");
if (!textInput) return;
textInput.addEventListener("mousedown", (e) => e.stopPropagation());
const autosize = () => {
textInput.style.height = "auto";
textInput.style.height = textInput.scrollHeight + 4 + "px";
};
textInput.addEventListener("input", autosize);
textInput.addEventListener("keydown", (e) => {
e.stopPropagation();
if (e.key === "Enter" && !e.shiftKey) {
e.preventDefault();
commitTextInput();
} else if (e.key === "Escape") {
e.preventDefault();
hideTextInput();
}
});
}
function bindGlobalListeners() {
document.addEventListener("keydown", onKeydown, true);
document.addEventListener("keyup", onKeyup, true);
document.addEventListener("paste", onPaste, true);
window.addEventListener("blur", () => {
if (S.spaceDown) {
S.spaceDown = false;
updateCursor();
}
if (S.panning) {
S.panning = false;
S.panStart = null;
updateCursor();
}
S._shiftDown = false;
endAltPicker();
});
bindIf(".iwb-editor-modal", "mousedown", (e) => e.stopPropagation());
}
function commitPenPath() {
if (!S.penPath || S.penPath.pts.length < 2) {
S.penPath = null;
renderObjects();
return;
}
saveSnapshot();
const shape = { id: "s" + Date.now() + Math.floor(Math.random() * 1e3), type: "pen", pts: S.penPath.pts.slice(), closed: !!S.penPath.closed, color: S.color, lw: Math.max(1, S.shapeLineWidth), fill: !!S.penFill && !!S.penPath.closed, opacity: 1, visible: true, locked: false, z: ++S.zCounter };
S.shapeLayers.push(shape);
S.penPath = null;
renderObjects();
renderLayerPanel();
finishCreateTool("shape", shape.id);
}
function bindCanvasEvents() {
if (S._canvasEventsBound) return;
S._canvasEventsBound = true;
S.canvasStack.addEventListener("mousedown", onMouseDown);
S.canvasStack.addEventListener("mousemove", onMouseMove);
S.canvasStack.addEventListener("mousemove", onCanvasHover);
window.addEventListener("mouseup", onMouseUp);
S.canvasStack.addEventListener("contextmenu", (e) => {
e.preventDefault();
if (S.open && !S.placingImage) showSelectionContext(e);
});
S.canvasStack.addEventListener("mouseleave", () => {
if (S.placingImage) return;
S.hoverPos = null;
if ((S.tool === "brush" || S.tool === "eraser") && !S.isDrawing) clearToolRing();
if (S.tool === "picker") hidePickerTip();
});
}
var CROP_CURSORS = {
nw: "nwse-resize",
se: "nwse-resize",
ne: "nesw-resize",
sw: "nesw-resize",
n: "ns-resize",
s: "ns-resize",
e: "ew-resize",
w: "ew-resize"
};
var HOVER_HANDLERS = {
select: onHoverSelect,
marquee: onHoverCrosshair,
lasso: onHoverCrosshair,
picker: onHoverPicker,
hand: onHoverHand,
brush: onHoverBrushRing,
eraser: onHoverBrushRing,
crop: onHoverCrop,
text: onHoverText,
pen: onHoverCrosshair,
rect: onHoverShape,
arrow: onHoverShape,
circle: onHoverShape
};
function onCanvasHover(e) {
if (S.placingImage) return;
if (S.panning || S.spaceDown) return;
if (S.isDrawing || S.textDrag || S.shapeDrag) return;
const p = getPos(e);
if (!S.lastPos || Math.abs(p.x - S.lastPos.x) > 0.5 || Math.abs(p.y - S.lastPos.y) > 0.5) {
S.lastPos = p;
updateStatusbar();
}
S.hoverPos = p;
if (isOverRotationHandle(p)) {
S.drawCanvasCursor(ROT_CURSOR);
return;
}
const handler = Object.prototype.hasOwnProperty.call(HOVER_HANDLERS, S.tool) ? HOVER_HANDLERS[S.tool] : null;
if (handler) handler(p, e);
else S.drawCanvasCursor("crosshair");
}
function onHoverSelect(p) {
const th = hitTextHandle(p);
if (th) {
S.drawCanvasCursor(th === "nw" || th === "se" ? "nwse-resize" : "nesw-resize");
return;
}
const shh = hitShapeHandle(p);
if (shh) {
const sh = getSelectedShape();
if (sh && sh.type === "rect" && CROP_CURSORS[shh]) S.drawCanvasCursor(CROP_CURSORS[shh]);
else S.drawCanvasCursor("move");
return;
}
S.drawCanvasCursor(hitAnyObject(p) ? "move" : "default");
}
function onHoverPicker(p, e) {
S.drawCanvasCursor("crosshair");
showPickerTip(e, sampleColor(p));
}
function onHoverHand() {
S.drawCanvasCursor("grab");
}
function onHoverBrushRing(p) {
S.drawCanvasCursor("none");
drawToolRing(p);
}
function onHoverCrop(p) {
if (S.cropRect) {
const h = hitCropHandle(p);
if (h && CROP_CURSORS[h]) {
S.drawCanvasCursor(CROP_CURSORS[h]);
return;
}
if (insideRect(p, S.cropRect)) {
S.drawCanvasCursor("move");
return;
}
}
S.drawCanvasCursor("crosshair");
}
function onHoverText(p) {
const h = hitTextHandle(p);
if (h) {
S.drawCanvasCursor(h === "nw" || h === "se" ? "nwse-resize" : "nesw-resize");
return;
}
S.drawCanvasCursor(hitTextLayer(p) ? "move" : "text");
}
function onHoverCrosshair() {
S.drawCanvasCursor("crosshair");
}
function onHoverShape(p) {
const h = hitShapeHandle(p);
if (h) {
const sh = getSelectedShape();
if (sh && sh.type === "rect" && CROP_CURSORS[h]) S.drawCanvasCursor(CROP_CURSORS[h]);
else S.drawCanvasCursor("move");
return;
}
S.drawCanvasCursor("crosshair");
}
function isTyping(e) {
const t = e.target;
if (!t) return false;
if (t.tagName === "TEXTAREA") return true;
if (t.tagName !== "INPUT") return false;
const cls = t.classList;
if (cls && (cls.contains("iwb-editor-text-input") || cls.contains("iwb-editor-color-hex-input"))) return true;
if (e.ctrlKey || e.metaKey || e.altKey || e.shiftKey) return false;
if (e.key === "Delete" || e.key === "Escape") return false;
return true;
}
function onKeydown(e) {
if (!S.open) return;
if (S.placingImage) {
if (e.key === "Enter") {
e.preventDefault();
confirmImagePlacement();
return;
}
if (e.key === "Escape") {
e.preventDefault();
cancelImagePlacement();
return;
}
}
if (e.key === "Shift") S._shiftDown = true;
if (e.key === "Alt" && !e.ctrlKey && !e.metaKey) {
e.preventDefault();
beginAltPicker();
return;
}
if (e.key === "Enter" && S.tool === "pen" && S.penPath) {
e.preventDefault();
commitPenPath();
return;
}
if (e.key === "Enter" && S.tool === "crop" && S.cropRect) {
e.preventDefault();
confirmCrop();
return;
}
if (e.key === "Escape") {
if (isTyping(e)) {
hideTextInput();
return;
}
if (closeColorPop()) {
e.preventDefault();
return;
}
if (S.tool === "crop" && S.cropRect) {
e.preventDefault();
cancelCrop();
return;
}
if (S.marquee || S.lassoPts || S.selection && S.selection.active) {
e.preventDefault();
clearMarquee();
return;
}
if (S.penPath) {
e.preventDefault();
S.penPath = null;
renderObjects();
return;
}
if (getPenEditingShape()) {
e.preventDefault();
exitPenEdit();
return;
}
if (S.selectedLayerId || S.selectedTextId || S.selectedShapeId || S.bitmapDrag || S.textDrag || S.shapeDrag) {
e.preventDefault();
clearSelection();
renderObjects();
renderLayerPanel();
}
return;
}
if (isTyping(e)) return;
const mod = e.ctrlKey || e.metaKey;
const key = String(e.key || "").toLowerCase();
const letterTools = {
v: "select",
m: "marquee",
l: "lasso",
b: "brush",
e: "eraser",
p: "pen",
t: "text",
u: "rect",
c: "crop",
i: "picker",
h: "hand"
};
if (!mod && !e.altKey && Object.prototype.hasOwnProperty.call(letterTools, key)) {
e.preventDefault();
if (e.shiftKey && key === "u") {
const cycle = { rect: "circle", circle: "arrow", arrow: "rect" };
setTool(cycle[S.tool] || "rect");
} else if (e.shiftKey && key === "m") {
S.selectionKind = S.selectionKind === "ellipse" ? "rect" : "ellipse";
setTool("marquee");
toast("选区形状:" + (S.selectionKind === "ellipse" ? "椭圆" : "矩形"), "info");
renderOptionBar(true);
} else {
setTool(letterTools[key]);
}
return;
}
if (!mod && !e.altKey && key === "tab") {
e.preventDefault();
togglePanelsCollapsed();
return;
}
if (!mod && e.shiftKey && key === "x") {
const sh = getSelectedShape();
if (sh && !sh.locked) {
e.preventDefault();
if (sh.type === "arrow") {
toast("箭头没有实心样式", "info");
return;
}
setShapeFill(!sh.fill, sh.type === "pen" ? "pen" : "rect");
}
return;
}
const isBracket = e.key === "[" || e.key === "]" || e.code === "BracketLeft" || e.code === "BracketRight";
if (!mod && !e.altKey && isBracket) {
e.preventDefault();
const step = S.brushSize >= 64 ? 8 : S.brushSize >= 24 ? 4 : S.brushSize >= 8 ? 2 : 1;
S.brushSize = clamp(S.brushSize + (e.key === "]" ? step : -step), 1, 300);
syncOptionBar();
updateCursor();
refreshBrushRing();
return;
}
if (mod && !e.shiftKey && e.key === "0") {
e.preventDefault();
setZoomFit();
return;
}
if (mod && !e.shiftKey && e.key === "1") {
e.preventDefault();
setZoomActual();
return;
}
if (mod && (e.key === "+" || e.key === "=")) {
e.preventDefault();
zoomStep(ZOOM_STEP, S.canvasWrap.clientWidth / 2, S.canvasWrap.clientHeight / 2);
return;
}
if (mod && e.key === "-") {
e.preventDefault();
zoomStep(1 / ZOOM_STEP, S.canvasWrap.clientWidth / 2, S.canvasWrap.clientHeight / 2);
return;
}
if (mod && key === "a") {
e.preventDefault();
runCommand("sel.all");
return;
}
if (mod && e.shiftKey && key === "i") {
e.preventDefault();
runCommand("sel.invert");
return;
}
if (mod && key === "d") {
e.preventDefault();
runCommand("sel.none");
return;
}
if (mod && key === "j") {
e.preventDefault();
runCommand("sel.copy");
return;
}
if (mod && key === "x" && S.selection && S.selection.active) {
e.preventDefault();
runCommand("sel.cut");
return;
}
if (mod && key === "e") {
e.preventDefault();
const r = e.shiftKey ? mergeVisibleLayers() : mergeLayers();
toast(r.msg, r.ok ? "success" : "warn");
return;
}
if (mod && e.shiftKey && key === "n") {
e.preventDefault();
addBlankLayer();
return;
}
if (mod && !e.shiftKey && key === "o") {
e.preventDefault();
const b = runtime.el && runtime.el.querySelector('[data-action="addBitmapLayer"]');
if (b) b.click();
return;
}
if (mod && key === "s") {
e.preventDefault();
const b = runtime.el && runtime.el.querySelector('[data-action="download"]');
if (b) b.click();
return;
}
if (e.key === "Delete" || e.key === "Backspace") {
if (S.selection && S.selection.active && !S.selectedTextId && !S.selectedShapeId) {
e.preventDefault();
runCommand("sel.delete");
return;
}
if (S.selectedTextId) {
e.preventDefault();
deleteSelectedText();
renderLayerPanel();
return;
}
if (S.selectedShapeId) {
e.preventDefault();
deleteSelectedShape();
renderLayerPanel();
return;
}
if (S.selectedLayerId && S.selectedLayerId !== "base") {
e.preventDefault();
deleteLayer(S.selectedLayerId);
renderLayerPanel();
return;
}
}
if (e.code === "Space") {
e.preventDefault();
if (!S.spaceDown) {
S.spaceDown = true;
updateCursor();
}
return;
}
if (e.code === "BracketLeft" || e.code === "BracketRight") {
const up = e.code === "BracketRight";
if (mod) {
e.preventDefault();
moveLayer(e.shiftKey ? up ? "top" : "bottom" : up ? "up" : "down");
return;
}
if (e.altKey) {
e.preventDefault();
selectNeighborLayer(up);
return;
}
}
if (mod && key === "z") {
e.preventDefault();
if (e.shiftKey) redo();
else undo();
return;
}
if (mod && key === "y") {
e.preventDefault();
redo();
return;
}
}
function onKeyup(e) {
if (e.key === "Shift") S._shiftDown = false;
if (e.key === "Alt") endAltPicker();
if (e.code === "Space" && S.spaceDown) {
S.spaceDown = false;
updateCursor();
}
}
function onPaste(e) {
if (!S.open) return;
const cd = e.clipboardData;
if (!cd) return;
const items = cd.items || [];
for (const item of items) {
if (item.kind === "file" && /^image\//.test(item.type)) {
const file = item.getAsFile();
if (!file) continue;
e.preventDefault();
e.stopImmediatePropagation();
const reader = new FileReader();
reader.onload = async () => {
try {
addBitmapLayer(await loadImage(reader.result));
} catch (err) {
console.error("[IWB编辑器] 粘贴图层失败:", err);
}
};
reader.readAsDataURL(file);
return;
}
}
if (isTyping(e)) return;
const html = typeof cd.getData === "function" ? cd.getData("text/html") || "" : "";
if (html) {
const m = /<img[^>]*\ssrc\s*=\s*["']([^"']+)["']/i.exec(html);
if (m) {
e.preventDefault();
e.stopImmediatePropagation();
pasteImageFromUrl(m[1]);
return;
}
}
const text = (typeof cd.getData === "function" ? cd.getData("text/plain") || "" : "").trim();
if (/^(https?:\/\/\S+|data:image\/\S+)$/i.test(text)) {
e.preventDefault();
e.stopImmediatePropagation();
pasteImageFromUrl(text);
return;
}
}
async function pasteImageFromUrl(url) {
try {
let dataUrl = url;
if (!/^data:image\//i.test(url)) {
const resp = await fetch(url);
if (!resp.ok) throw new Error("HTTP " + resp.status);
const blob = await resp.blob();
if (!/^image\//.test(blob.type)) throw new Error("链接不是图片(" + (blob.type || "未知类型") + ")");
dataUrl = await new Promise((resolve, reject) => {
const reader = new FileReader();
reader.onload = () => resolve(reader.result);
reader.onerror = () => reject(new Error("图片读取失败"));
reader.readAsDataURL(blob);
});
}
addBitmapLayer(await loadImage(dataUrl));
} catch (err) {
console.error("[IWB编辑器] 粘贴图片链接失败:", err);
toast("粘贴失败:" + (err && err.message || "无法读取剪贴板里的图片链接"), "error");
}
}
// image-annotate/plugin/editor/viewport.js
function syncOverlayCanvas() {
const pad = S.overlayPad || 0;
const scale = S.imgW ? S.fitW * S.zoom / S.imgW : 1;
const w = Math.round((S.imgW + pad * 2) * scale) + "px";
const h = Math.round((S.imgH + pad * 2) * scale) + "px";
for (const c of [S.overlayCanvas, S.selectionCanvas, S.cursorCanvas]) {
if (!c) continue;
c.style.left = "0px";
c.style.top = "0px";
c.style.width = w;
c.style.height = h;
}
}
function setupCanvas(img) {
purgeVectorCanvases();
for (const layer of S.layers) {
if (layer.canvas.parentNode) layer.canvas.parentNode.removeChild(layer.canvas);
}
S.layers = [];
S.textCanvas.width = S.imgW;
S.textCanvas.height = S.imgH;
S.strokeCanvas.width = S.imgW;
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 = 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 });
baseCtx.clearRect(0, 0, S.imgW, S.imgH);
baseCtx.drawImage(img, 0, 0);
S.layers.push({
id: "base",
name: "原图",
canvas: baseCanvas,
ctx: baseCtx,
opacity: 1,
visible: true,
locked: true,
z: 0
});
S.activeLayerId = "base";
S.zCounter = 1;
S.textCtx.clearRect(0, 0, S.imgW, S.imgH);
S.strokeCtx.clearRect(0, 0, S.imgW, S.imgH);
clearOverlay();
S.pickerComposite = null;
renderObjects();
S.viewX = null;
applyView();
renderLayerPanel();
bindCanvasEvents();
}
function resizeWorkspace(w, h) {
S.imgW = Math.max(1, Math.round(w));
S.imgH = Math.max(1, Math.round(h));
S.textCanvas.width = S.imgW;
S.textCanvas.height = S.imgH;
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 = 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) {
layer.canvas.width = S.imgW;
layer.canvas.height = S.imgH;
layer._bounds = void 0;
}
S.pickerComposite = null;
clearOverlay();
S.viewX = null;
applyView();
renderObjects();
renderLayerPanel();
}
function computeFit() {
const TOOLBAR_RESERVE = 72;
const availW = Math.max(50, S.canvasWrap.clientWidth - 48);
const availH = Math.max(50, S.canvasWrap.clientHeight - 48 - TOOLBAR_RESERVE);
const ratio = Math.min(availW / S.imgW, availH / S.imgH);
S.fitW = Math.max(1, S.imgW * ratio);
S.fitH = Math.max(1, S.imgH * ratio);
}
function applyView(anchor) {
const w = Math.round(S.fitW * S.zoom);
const h = Math.round(S.fitH * S.zoom);
for (const layer of S.layers) {
layer.canvas.style.width = w + "px";
layer.canvas.style.height = h + "px";
}
S.textCanvas.style.width = S.strokeCanvas.style.width = w + "px";
S.textCanvas.style.height = S.strokeCanvas.style.height = h + "px";
syncOverlayCanvas();
const scale = S.imgW ? S.fitW * S.zoom / S.imgW : 1;
if (S.transparencyGrid) {
S.transparencyGrid.style.left = Math.round((S.overlayPad || 0) * scale) + "px";
S.transparencyGrid.style.top = Math.round((S.overlayPad || 0) * scale) + "px";
S.transparencyGrid.style.width = w + "px";
S.transparencyGrid.style.height = h + "px";
}
const pad = S.overlayPad || 0;
S.canvasStack.style.width = Math.round((S.imgW + pad * 2) * scale) + "px";
S.canvasStack.style.height = Math.round((S.imgH + pad * 2) * scale) + "px";
const layerOffset = Math.round(pad * scale);
for (const layer of S.layers) {
layer.canvas.style.left = layerOffset + "px";
layer.canvas.style.top = layerOffset + "px";
}
S.textCanvas.style.left = layerOffset + "px";
S.textCanvas.style.top = layerOffset + "px";
S.strokeCanvas.style.left = layerOffset + "px";
S.strokeCanvas.style.top = layerOffset + "px";
styleVectorViewport(w, h, layerOffset);
let left, top;
if (anchor && anchor.mx !== void 0) {
left = anchor.mx - anchor.px * S.zoom;
top = anchor.my - anchor.py * S.zoom;
} else if (S.viewX !== null) {
left = S.viewX;
top = S.viewY;
} else {
left = (S.canvasWrap.clientWidth - w) / 2;
top = (S.canvasWrap.clientHeight - h) / 2;
}
setView(left, top);
updateZoomUI();
}
function setView(x, y) {
S.viewX = x;
S.viewY = y;
const stack = S.canvasStack;
const scale = S.imgW ? S.fitW * S.zoom / S.imgW : 1;
const pad = S.overlayPad || 0;
stack.style.transform = `translate3d(${Math.round(x - pad * scale)}px, ${Math.round(y - pad * scale)}px, 0)`;
}
function zoomStep(factor, mx, my) {
const nz = clamp(S.zoom * factor, ZOOM_MIN, ZOOM_MAX);
if (nz === S.zoom) return;
const px = (mx - (S.viewX || 0)) / S.zoom;
const py = (my - (S.viewY || 0)) / S.zoom;
S.zoom = nz;
applyView({ mx, my, px, py });
}
function setZoomFit() {
computeFit();
S.zoom = 1;
S.viewX = null;
applyView();
}
function setZoomActual() {
computeFit();
S.zoom = clamp(S.fitW ? S.imgW / S.fitW : 1, ZOOM_MIN, ZOOM_MAX);
S.viewX = null;
applyView();
}
function clamp(v, min, max) {
return Math.max(min, Math.min(max, v));
}
function rotPt(px, py, cx, cy, deg) {
if (!deg) return [px, py];
const a = deg * Math.PI / 180, sn = Math.sin(a), cs = Math.cos(a);
const dx = px - cx, dy = py - cy;
return [cx + dx * cs - dy * sn, cy + dx * sn + dy * cs];
}
function unrotPt(px, py, cx, cy, deg) {
return rotPt(px, py, cx, cy, -(deg || 0));
}
function rotationHandlesLocal(b) {
const cx = b.x + b.w / 2, cy = b.y + b.h / 2;
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];
});
}
function hitRotationHandle(lp, b) {
const pts = rotationHandlesLocal(b);
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;
}
return false;
}
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(viewScale(), 1e-4);
const r = 6.5 / k;
const lw = 1.5 / k;
const ah = 3 / k;
const A0 = Math.PI * 0.2, A1 = Math.PI * 1.72;
ctx.save();
ctx.strokeStyle = "#f0b34e";
ctx.fillStyle = "#f0b34e";
ctx.lineWidth = lw;
ctx.lineCap = "round";
for (const pt of pts) {
const w = rotPt(pt[0], pt[1], cx, cy, rot || 0);
ctx.beginPath();
ctx.arc(w[0], w[1], r, A0, A1);
ctx.stroke();
const ex = w[0] + Math.cos(A1) * r, ey = w[1] + Math.sin(A1) * r;
const ta = A1 + Math.PI / 2;
ctx.beginPath();
ctx.moveTo(ex + Math.cos(ta) * ah * 1.4, ey + Math.sin(ta) * ah * 1.4);
ctx.lineTo(ex + Math.cos(ta + 2.4) * ah, ey + Math.sin(ta + 2.4) * ah);
ctx.lineTo(ex + Math.cos(ta - 2.4) * ah, ey + Math.sin(ta - 2.4) * ah);
ctx.closePath();
ctx.fill();
}
ctx.restore();
}
var ROT_CURSOR = `url("data:image/svg+xml;utf8,<svg xmlns='http://www.w3.org/2000/svg' width='24' height='24' viewBox='0 0 24 24' fill='none' stroke='black' stroke-width='2' stroke-linecap='round'><path d='M21 12a9 9 0 1 1-3-6.7'/><polyline points='21 3 21 9 15 9'/></svg>") 12 12, crosshair`;
function isOverRotationHandle(p) {
if (S.placingImage) {
const b = { x: S.placingImage.x, y: S.placingImage.y, w: S.placingImage.w, h: S.placingImage.h };
const lp = unrotPt(p.x, p.y, b.x + b.w / 2, b.y + b.h / 2, S.placingImage.rotation || 0);
return hitRotationHandle(lp, b);
}
const t = getSelectedText();
if (t) {
const b = textBounds(t);
const lp = unrotPt(p.x, p.y, b.x + b.w / 2, b.y + b.h / 2, t.rotation || 0);
return hitRotationHandle(lp, b);
}
const sh = getSelectedShape();
if (sh) {
const b = shapeBounds(sh);
const lp = unrotPt(p.x, p.y, b.x + b.w / 2, b.y + b.h / 2, sh.rotation || 0);
return hitRotationHandle(lp, b);
}
const layer = S.layers.find((l) => l.id === S.selectedLayerId && l.transformable);
if (layer) {
const lp = unrotPt(p.x, p.y, layer.x + layer.w / 2, layer.y + layer.h / 2, layer.rotation || 0);
return hitRotationHandle(lp, layer);
}
return false;
}
function boxCorners(x, y, w, h, rot) {
const cx = x + w / 2, cy = y + h / 2;
return [[x, y], [x + w, y], [x + w, y + h], [x, y + h]].map((pt) => rotPt(pt[0], pt[1], cx, cy, rot));
}
function getPos(e) {
const rect = S.canvasStack.getBoundingClientRect();
const pad = S.overlayPad || 0;
const scale = S.imgW ? S.fitW * S.zoom / S.imgW : 1;
return {
x: (e.clientX - rect.left) / Math.max(scale, 1e-4) - pad,
y: (e.clientY - rect.top) / Math.max(scale, 1e-4) - pad
};
}
// image-annotate/plugin/editor/crop.js
function setConstraint(type, ratio, sizeW, sizeH) {
S.cropConstraint = { type, ratio: ratio || 0, sizeW: sizeW || 0, sizeH: sizeH || 0 };
const toggle = runtime.el && runtime.el.querySelector(".iwb-editor-size-toggle");
if (toggle) {
const active = type === "size";
toggle.classList.toggle("active", active);
toggle.setAttribute("aria-pressed", String(active));
toggle.textContent = active ? "已启用" : "启用尺寸";
}
if (S.cropRect) {
S.cropRect = applyConstraint(S.cropRect.x, S.cropRect.y, S.cropRect.w, S.cropRect.h);
drawCropPreview();
updateCropInfo();
}
}
function applyConstraint(x, y, w, h) {
const c = S.cropConstraint;
if (c.type === "free" || !c.ratio || c.ratio <= 0) return { x, y, w, h };
const ratio = c.ratio;
if (w / h > ratio) {
const nw = h * ratio;
const dx = (w - nw) / 2;
return { x: x + dx, y, w: nw, h };
} else {
const nh = w / ratio;
const dy = (h - nh) / 2;
return { x, y: y + dy, w, h: nh };
}
}
function applyConstraintDrag(x1, y1, x2, y2) {
const c = S.cropConstraint;
let rx = Math.min(x1, x2), ry = Math.min(y1, y2);
let rw = Math.abs(x2 - x1), rh = Math.abs(y2 - y1);
if (rw < 1) rw = 1;
if (rh < 1) rh = 1;
if (c.type === "free" || !c.ratio || c.ratio <= 0) return { x: rx, y: ry, w: rw, h: rh };
const ratio = c.ratio;
if (rw / rh > ratio) {
rh = rw / ratio;
} else {
rw = rh * ratio;
}
return { x: rx, y: ry, w: rw, h: rh };
}
function updateCropInfo() {
const info = runtime.el.querySelector(".iwb-editor-crop-info");
if (!info) return;
if (S.cropRect) {
const w = Math.round(S.cropRect.w);
const h = Math.round(S.cropRect.h);
const c = S.cropConstraint;
if (c.type === "size" && c.sizeW > 0 && c.sizeH > 0) {
info.textContent = `${w}x${h} -> ${c.sizeW}x${c.sizeH}`;
} else {
info.textContent = `${w}x${h}`;
}
} else {
info.textContent = "--";
}
}
function clearOverlay() {
const ctx = S.overlayCtx;
if (!ctx) return;
ctx.save();
ctx.setTransform(1, 0, 0, 1, 0, 0);
ctx.clearRect(0, 0, ctx.canvas.width, ctx.canvas.height);
ctx.restore();
resetOverlayTransform(ctx);
}
function drawCropPreview(x1, y1, x2, y2) {
const ctx = S.overlayCtx;
clearOverlay();
let rx, ry, rw, rh;
if (x2 !== void 0) {
const r = applyConstraintDrag(x1, y1, x2, y2);
rx = r.x;
ry = r.y;
rw = r.w;
rh = r.h;
} else if (S.cropRect) {
rx = S.cropRect.x;
ry = S.cropRect.y;
rw = S.cropRect.w;
rh = S.cropRect.h;
} else {
return;
}
ctx.save();
ctx.fillStyle = "rgba(0,0,0,0.45)";
const cropPad = Math.max(S.imgW, S.imgH) * 2;
ctx.fillRect(-cropPad, -cropPad, S.imgW + cropPad * 2, S.imgH + cropPad * 2);
ctx.globalCompositeOperation = "destination-out";
ctx.fillRect(rx, ry, rw, rh);
ctx.restore();
ctx.save();
ctx.strokeStyle = "#4488ff";
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);
}
function cropHandlePoints(rx, ry, rw, rh) {
return {
nw: [rx, ry],
ne: [rx + rw, ry],
sw: [rx, ry + rh],
se: [rx + rw, ry + rh],
n: [rx + rw / 2, ry],
s: [rx + rw / 2, ry + rh],
e: [rx + rw, ry + rh / 2],
w: [rx, ry + rh / 2]
};
}
function drawCropHandles(rx, ry, rw, rh) {
const ctx = S.overlayCtx;
const pts = cropHandlePoints(rx, ry, rw, rh);
const hs = 4 / viewScale();
ctx.save();
ctx.fillStyle = "#ffffff";
ctx.strokeStyle = "#4488ff";
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);
ctx.fill();
ctx.stroke();
}
ctx.restore();
}
function insideRect(pos, rect) {
return pos.x >= rect.x && pos.x <= rect.x + rect.w && pos.y >= rect.y && pos.y <= rect.y + rect.h;
}
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 / viewScale();
let best = null, bestDist = 1e9;
for (const name in pts) {
const dx = pos.x - pts[name][0], dy = pos.y - pts[name][1];
const d = dx * dx + dy * dy;
if (d < R * R && d < bestDist) {
bestDist = d;
best = name;
}
}
return best;
}
function resizeCropRect(pos) {
if (!S.cropRect) return;
const { x, y, w, h } = S.cropRect;
const c = S.cropConstraint;
let nx = x, ny = y, nw = w, nh = h;
const hh = S.cropHandle;
if (c.type === "free" || !c.ratio || c.ratio <= 0) {
if (hh.includes("e")) nw = Math.max(4, pos.x - x);
if (hh.includes("s")) nh = Math.max(4, pos.y - y);
if (hh.includes("w")) {
const right = x + w;
nx = Math.min(pos.x, right - 4);
nw = right - nx;
}
if (hh.includes("n")) {
const bottom = y + h;
ny = Math.min(pos.y, bottom - 4);
nh = bottom - ny;
}
S.cropRect = { x: nx, y: ny, w: nw, h: nh };
return;
}
const ratio = c.ratio;
if (hh === "e" || hh === "w") {
if (hh === "e") {
nw = Math.max(4, pos.x - x);
} else {
const right = x + w;
nx = Math.min(pos.x, right - 4);
nw = right - nx;
}
nh = nw / ratio;
} else if (hh === "n" || hh === "s") {
if (hh === "s") {
nh = Math.max(4, pos.y - y);
} else {
const bottom = y + h;
ny = Math.min(pos.y, bottom - 4);
nh = bottom - ny;
}
nw = nh * ratio;
} else {
if (hh === "se") {
nw = Math.max(4, pos.x - x);
nh = Math.max(4, pos.y - y);
} else if (hh === "ne") {
nw = Math.max(4, pos.x - x);
const bottom = y + h;
ny = Math.min(pos.y, bottom - 4);
nh = bottom - ny;
} else if (hh === "sw") {
const right = x + w;
nx = Math.min(pos.x, right - 4);
nw = right - nx;
nh = Math.max(4, pos.y - y);
} else if (hh === "nw") {
const right = x + w;
nx = Math.min(pos.x, right - 4);
nw = right - nx;
const bottom = y + h;
ny = Math.min(pos.y, bottom - 4);
nh = bottom - ny;
}
if (nw / nh > ratio) {
nh = nw / ratio;
if (hh === "ne" || hh === "nw") ny = y + h - nh;
} else {
nw = nh * ratio;
if (hh === "nw" || hh === "sw") nx = x + w - nw;
}
}
S.cropRect = { x: nx, y: ny, w: nw, h: nh };
}
function confirmCrop() {
if (!S.cropRect) return;
const { x, y, w, h } = S.cropRect;
if (w < 2 || h < 2) {
cancelCrop();
return;
}
const c = S.cropConstraint;
const sx = Math.round(x), sy = Math.round(y);
const sw = Math.max(1, Math.round(w)), sh = Math.max(1, Math.round(h));
const isSize = c.type === "size" && c.sizeW > 0 && c.sizeH > 0;
const nw = isSize ? Math.max(1, Math.round(c.sizeW)) : sw;
const nh = isSize ? Math.max(1, Math.round(c.sizeH)) : sh;
if (nw === S.imgW && nh === S.imgH && sx === 0 && sy === 0) {
cancelCrop();
return;
}
const oldW = S.imgW, oldH = S.imgH;
const scaleX = nw / sw, scaleY = nh / sh;
const srcX = Math.max(0, sx), srcY = Math.max(0, sy);
const srcW = Math.max(0, Math.min(oldW, sx + sw) - srcX);
const srcH = Math.max(0, Math.min(oldH, sy + sh) - srcY);
const dstX = (srcX - sx) * scaleX, dstY = (srcY - sy) * scaleY;
const dstW = srcW * scaleX, dstH = srcH * scaleY;
saveSnapshot("裁剪");
disposeSelection();
const staged = S.layers.map((layer) => {
const tmp = document.createElement("canvas");
tmp.width = nw;
tmp.height = nh;
if (srcW > 0 && srcH > 0) {
try {
tmp.getContext("2d").drawImage(layer.canvas, srcX, srcY, srcW, srcH, dstX, dstY, dstW, dstH);
} catch (e) {
}
}
return tmp;
});
resizeWorkspace(nw, nh);
S.layers.forEach((layer, i) => {
const tmp = staged[i];
try {
layer.ctx.drawImage(tmp, 0, 0);
} catch (e) {
}
tmp.width = 0;
tmp.height = 0;
layer.x = 0;
layer.y = 0;
layer.w = nw;
layer.h = nh;
layer.rotation = 0;
layer.transformable = false;
layer.image = null;
layer.sourceCanvas = null;
layer._srcBox = null;
layer._bounds = void 0;
});
S.textLayers = S.textLayers.map((t) => ({
...t,
x: (t.x - sx) * scaleX,
y: (t.y - sy) * scaleY,
fontSize: t.fontSize * scaleX
}));
S.shapeLayers = S.shapeLayers.map((s) => ({
...s,
...s.type === "pen" ? { pts: (s.pts || []).map((p) => ({ x: (p.x - sx) * scaleX, y: (p.y - sy) * scaleY })) } : {
x1: (s.x1 - sx) * scaleX,
y1: (s.y1 - sy) * scaleY,
x2: (s.x2 - sx) * scaleX,
y2: (s.y2 - sy) * scaleY
},
lw: Math.max(1, s.lw * (scaleX + scaleY) / 2)
}));
S.selectedTextId = null;
S.textDrag = null;
S.selectedShapeId = null;
S.shapeDrag = null;
S.selectedLayerId = null;
S.bitmapDrag = null;
S.zoom = 1;
S.cropRect = null;
S.cropHandle = null;
S.cropMoving = false;
S.moveStart = null;
updateCropInfo();
if (S.renderAll) S.renderAll();
toast("已裁剪为 " + nw + "×" + nh + "(Ctrl+Z 可撤销)", "success");
}
function cancelCrop() {
S.cropRect = null;
S.cropHandle = null;
S.cropMoving = false;
S.moveStart = null;
clearOverlay();
updateCropInfo();
}
function showCropBar() {
}
function hideCropBar() {
}
// image-annotate/plugin/editor/history.js
var snapshotStats = { snapshots: 0, getImageDataCalls: 0, bytesWritten: 0 };
function cloneVectors(arr) {
return JSON.parse(JSON.stringify(arr || [], (key, value) => {
if (key === "_canvas" || key === "_ctx") return void 0;
return value;
}));
}
function snapshotState(opts) {
const metaOnly = !!(opts && opts.metaOnly);
const bitmaps = S.layers.map((layer) => {
let data = null;
if (!metaOnly && needsPixelSnapshot(layer)) {
try {
data = layer.ctx.getImageData(0, 0, S.imgW, S.imgH);
} catch (e) {
}
if (data) {
snapshotStats.getImageDataCalls++;
snapshotStats.bytesWritten += data.data.byteLength;
}
}
return {
id: layer.id,
data,
// ---- 图层重建所需元数据(v1.1)----
name: layer.name,
z: layer.z,
opacity: layer.opacity,
visible: layer.visible,
locked: !!layer.locked,
transformable: !!layer.transformable,
color: layer.color,
lineWidth: layer.lineWidth,
imageRef: layer.image || null,
sourceRef: layer.sourceCanvas || null,
sourceBox: layer._srcBox ? { ...layer._srcBox } : null,
x: layer.x,
y: layer.y,
w: layer.w,
h: layer.h,
rotation: layer.rotation || 0
};
});
snapshotStats.snapshots++;
return {
imgW: S.imgW,
imgH: S.imgH,
activeLayerId: S.activeLayerId,
bitmaps,
texts: cloneVectors(S.textLayers),
shapes: cloneVectors(S.shapeLayers),
layerOrder: S.layers.map((l) => ({ id: l.id, name: l.name, z: l.z, opacity: l.opacity, visible: l.visible, locked: !!l.locked, x: l.x, y: l.y, w: l.w, h: l.h }))
};
}
var HISTORY_MAX_ENTRIES = 50;
var HISTORY_MAX_BYTES = 128 * 1024 * 1024;
var HISTORY_MIN_BYTES = 32 * 1024 * 1024;
function historyBudgetBytes() {
const px = (S.imgW || 0) * (S.imgH || 0) * 4;
if (!px) return HISTORY_MAX_BYTES;
return Math.min(HISTORY_MAX_BYTES, Math.max(HISTORY_MIN_BYTES, px * 4));
}
function stateBytes(state) {
let n = 0;
if (state && state.bitmaps) {
for (const b of state.bitmaps) {
if (b.data && b.data.data) n += b.data.data.byteLength;
}
}
if (state) {
n += state.texts ? JSON.stringify(state.texts).length * 2 : 0;
n += state.shapes ? JSON.stringify(state.shapes).length * 2 : 0;
}
return n;
}
function pushHistory(stack, state, label) {
state.__bytes = stateBytes(state);
if (label) state.__label = label;
stack.push(state);
const budget = historyBudgetBytes();
let total = stack.reduce((sum, s) => sum + (s.__bytes || 0), 0);
while (stack.length > 1 && (stack.length > HISTORY_MAX_ENTRIES || total > budget)) {
total -= stack.shift().__bytes || 0;
}
return state;
}
function saveSnapshot(label) {
pushHistory(S.history, snapshotState(), label);
S.redoStack = [];
}
function recreateLayer(bm) {
const canvas = createLayerCanvas();
const ctx = canvas.getContext("2d", { willReadFrequently: true });
return {
id: bm.id,
name: bm.name || "图层 " + bm.id,
canvas,
ctx,
opacity: bm.opacity == null ? 1 : bm.opacity,
visible: bm.visible !== false,
locked: !!bm.locked,
transformable: !!bm.transformable,
color: bm.color,
lineWidth: bm.lineWidth,
image: bm.imageRef || null,
sourceCanvas: bm.sourceRef || null,
_srcBox: bm.sourceBox || null,
x: bm.x,
y: bm.y,
w: bm.w,
h: bm.h,
rotation: bm.rotation || 0,
z: bm.z || 0
};
}
function releaseLayer(layer) {
try {
if (layer.canvas && layer.canvas.parentNode) layer.canvas.parentNode.removeChild(layer.canvas);
if (layer.canvas) {
layer.canvas.width = 0;
layer.canvas.height = 0;
}
} catch (e) {
}
}
function restoreState(state) {
if (state.imgW && state.imgH && (state.imgW !== S.imgW || state.imgH !== S.imgH)) {
purgeVectorCanvases();
for (const l of S.layers) releaseLayer(l);
S.layers = [];
resizeWorkspace(state.imgW, state.imgH);
}
purgeVectorCanvases();
for (const l of S.layers) l._bounds = void 0;
const snaps = state.bitmaps || [];
const want = new Set(snaps.map((b) => b.id));
for (let i = S.layers.length - 1; i >= 0; i--) {
if (!want.has(S.layers[i].id)) {
releaseLayer(S.layers[i]);
S.layers.splice(i, 1);
}
}
const ordered = [];
for (const bm of snaps) {
let layer = S.layers.find((l) => l.id === bm.id);
if (!layer) {
layer = recreateLayer(bm);
S.layers.push(layer);
if (bm.data) {
try {
layer.ctx.putImageData(bm.data, 0, 0);
} catch (e) {
}
} else if (restorePath(layer) === "redraw") {
redrawBitmapLayer(layer);
}
} else {
layer.x = bm.x;
layer.y = bm.y;
layer.w = bm.w;
layer.h = bm.h;
layer.locked = !!bm.locked;
layer.rotation = bm.rotation || 0;
if (isDrawableLayer(layer)) {
layer._srcBox = null;
layer.sourceCanvas = null;
layer.rotation = 0;
layer.x = 0;
layer.y = 0;
layer.w = S.imgW;
layer.h = S.imgH;
layer._bounds = void 0;
}
if (restorePath(layer) === "redraw") {
redrawBitmapLayer(layer);
} else if (bm.data) {
try {
layer.ctx.clearRect(0, 0, S.imgW, S.imgH);
layer.ctx.putImageData(bm.data, 0, 0);
} catch (e) {
}
}
}
ordered.push(layer);
}
S.layers = ordered;
if (state.layerOrder) {
for (const meta of state.layerOrder) {
const layer = S.layers.find((l) => l.id === meta.id);
if (layer) {
layer.name = meta.name;
layer.z = meta.z;
layer.opacity = meta.opacity == null ? 1 : meta.opacity;
layer.visible = meta.visible !== false;
}
}
}
if (!S.layers.some((l) => l.id === S.activeLayerId)) S.activeLayerId = S.layers.length ? S.layers[S.layers.length - 1].id : null;
if (state.activeLayerId && S.layers.some((l) => l.id === state.activeLayerId)) S.activeLayerId = state.activeLayerId;
S.zCounter = Math.max(S.zCounter, ...S.layers.map((l) => l.z || 0), ...(state.texts || []).map((t) => t.z || 0), ...(state.shapes || []).map((s) => s.z || 0));
S.textLayers = cloneVectors(state.texts);
S.shapeLayers = cloneVectors(state.shapes);
S.selectedTextId = null;
S.textDrag = null;
S.selectedShapeId = null;
S.shapeDrag = null;
S.selectedLayerId = null;
S.bitmapDrag = null;
S.penPath = null;
S.penEditId = null;
S.layerMulti.length = 0;
reorderLayerCanvas();
updateLayerCanvasStyles();
renderObjects();
renderLayerPanel();
updateCropInfo();
}
function undo() {
if (S.placingImage) return;
if (S.isDrawing || S.textDrag || S.shapeDrag || S.bitmapDrag) return;
if (S.history.length === 0) {
toast("没有可撤销的操作");
return;
}
pushHistory(S.redoStack, snapshotState());
restoreState(S.history.pop());
if (S.renderAll) S.renderAll();
}
function redo() {
if (S.placingImage) return;
if (S.isDrawing || S.textDrag || S.shapeDrag || S.bitmapDrag) return;
if (S.redoStack.length === 0) {
toast("没有可重做的操作");
return;
}
pushHistory(S.history, snapshotState());
restoreState(S.redoStack.pop());
if (S.renderAll) S.renderAll();
}
function restoreAll() {
if (!S.originalImage) return;
const img = S.originalImage;
const ow = img.naturalWidth || img.width;
const oh = img.naturalHeight || img.height;
const sizeChanged = ow !== S.imgW || oh !== S.imgH;
if (sizeChanged) {
S.imgW = ow;
S.imgH = oh;
S.zoom = 1;
setupCanvas(img);
S.history = [];
S.redoStack = [];
clearAllEditState();
updateAllUI();
if (S.renderAll) S.renderAll();
toast("已还原为原图(裁剪后的画布尺寸已复位)", "success");
return;
}
saveSnapshot("还原原图");
const base = S.layers.find((l) => l.id === "base");
for (const layer of S.layers) {
if (layer !== base) releaseLayer(layer);
}
if (base) {
base.ctx.clearRect(0, 0, S.imgW, S.imgH);
base.ctx.drawImage(img, 0, 0);
base.locked = true;
base.visible = true;
base.opacity = 1;
base.z = 0;
}
S.layers = base ? [base] : [];
S.activeLayerId = base ? "base" : null;
S.zCounter = 1;
clearAllEditState();
if (S.renderAll) S.renderAll();
renderLayerPanel();
hideTextInput();
toast("已还原为原图,Ctrl+Z 可撤销", "success");
}
function clearAllEditState() {
S.textLayers = [];
S.selectedTextId = null;
S.textDrag = null;
S.textEditingId = null;
S.shapeLayers = [];
S.selectedShapeId = null;
S.shapeDrag = null;
S.selectedLayerId = null;
S.bitmapDrag = null;
S.penPath = null;
S.penEditId = null;
S.layerMulti.length = 0;
S.cropRect = null;
S.cropHandle = null;
S.cropMoving = false;
S.moveStart = null;
S.selection = null;
S.marquee = null;
S.lassoPts = null;
S.pickerComposite = null;
clearOverlay();
updateCropInfo();
reorderLayerCanvas();
updateLayerCanvasStyles();
renderObjects();
}
function resetDraw() {
restoreAll();
}
function restoreOriginal() {
restoreAll();
}
// image-annotate/plugin/editor/export.js
var DEFAULT_EXPORT = Object.freeze({
preset: "original",
// original | ecom800
format: "png",
// png | jpeg | webp
bg: "transparent",
// transparent | white
maxKB: 0,
// 0 = 不限
size: 800
// 预设输出边长
});
var SETTINGS_KEY = {
preset: "exportPreset",
format: "exportFormat",
bg: "exportBg",
maxKB: "exportMaxKB",
size: "exportSize"
};
function settings() {
return S.callbacks && S.callbacks.settings;
}
function effectiveBg(o) {
o = o || S.exportOptions || DEFAULT_EXPORT;
return o.bg === "white" || o.format === "jpeg" ? "white" : "transparent";
}
function exportSignature(o) {
o = o || S.exportOptions || DEFAULT_EXPORT;
const ecom = o.preset === "ecom800";
return [o.preset, o.format, ecom ? o.size : "orig", effectiveBg(o), ecom ? o.maxKB : 0].join(":");
}
function loadExportOptions() {
const st = settings();
const get = (k, d) => {
let v = d;
if (st && typeof st.get === "function") {
try {
const got = st.get(SETTINGS_KEY[k]);
if (got !== void 0 && got !== null) v = got;
} catch (e) {
}
}
return v;
};
const preset = get("preset", DEFAULT_EXPORT.preset) === "ecom800" ? "ecom800" : "original";
const format = ["png", "jpeg", "webp"].indexOf(get("format", DEFAULT_EXPORT.format)) >= 0 ? get("format", DEFAULT_EXPORT.format) : "png";
const rawMax = get("maxKB", null);
const rawSize = get("size", null);
S.exportOptions = {
preset,
format,
// JPG 下背景直接收敛到白底,状态本身自洽,不靠 UI 撒谎
bg: format === "jpeg" ? "white" : get("bg", DEFAULT_EXPORT.bg) === "white" ? "white" : "transparent",
maxKB: preset === "ecom800" ? rawMax === null ? 500 : Math.max(0, Number(rawMax) || 0) : 0,
size: Math.max(64, Number(rawSize === null ? 800 : rawSize) || 800)
};
renderExportUI();
}
function setExportOption(key, value) {
if (!S.exportOptions) loadExportOptions();
const o = S.exportOptions;
const st = settings();
const persist = (k, v) => {
if (st && typeof st.set === "function") {
try {
st.set(SETTINGS_KEY[k], v);
} catch (e) {
}
}
};
if (key === "preset") {
o.preset = value === "ecom800" ? "ecom800" : "original";
o.maxKB = o.preset === "ecom800" ? 500 : 0;
persist("preset", o.preset);
persist("maxKB", o.maxKB);
} else if (key === "format") {
o.format = ["png", "jpeg", "webp"].indexOf(value) >= 0 ? value : "png";
persist("format", o.format);
if (o.format === "jpeg" && o.bg !== "white") {
o.bg = "white";
persist("bg", "white");
toast("JPG 不支持透明背景,已切换为白底", "info");
}
} else if (key === "bg") {
if (o.format === "jpeg") {
renderExportUI();
return;
}
o.bg = value === "white" ? "white" : "transparent";
persist("bg", o.bg);
} else if (key === "maxKB") {
o.maxKB = Math.max(0, Number(value) || 0);
persist("maxKB", o.maxKB);
} else if (key === "size") {
o.size = Math.max(64, Number(value) || 800);
persist("size", o.size);
}
renderExportUI();
}
function renderExportUI() {
const o = S.exportOptions || DEFAULT_EXPORT;
const root = runtime.el;
if (!root) return;
const ecom = o.preset === "ecom800";
const jpg = o.format === "jpeg";
root.querySelectorAll("[data-export-key]").forEach((btn) => {
const on = String(o[btn.dataset.exportKey]) === String(btn.dataset.exportValue);
btn.classList.toggle("active", on);
btn.setAttribute("aria-pressed", String(on));
});
root.querySelectorAll('[data-export-key="bg"]').forEach((btn) => {
const blocked = jpg && btn.dataset.exportValue === "transparent";
btn.disabled = blocked;
if (blocked) btn.title = "JPG 不支持透明背景,已自动使用白底";
else btn.removeAttribute("title");
});
root.querySelectorAll('[data-export-when="ecom800"]').forEach((row) => {
row.hidden = !ecom;
});
const summary = root.querySelector(".iwb-editor-export-summary");
if (summary) {
const size = ecom ? o.size + "×" + o.size : "原尺寸 " + S.imgW + "×" + S.imgH;
const limit = ecom && o.maxKB ? " · ≤" + o.maxKB + "KB" : "";
const bg = effectiveBg(o) === "white" ? "白底" : "透明";
const fmt = o.format === "jpeg" ? "JPG" : o.format === "webp" ? "WebP" : "PNG";
summary.textContent = size + " · " + fmt + " · " + bg + limit;
}
const note = root.querySelector(".iwb-editor-export-note");
if (note) {
const le = S.lastExport;
note.textContent = le && le.signature === exportSignature(o) ? "上次输出 " + le.width + "×" + le.height + " · " + Math.max(1, Math.round(le.bytes / 1024)) + "KB" : "一次只输出一个结果;设置会记住";
}
}
function bindExportUI() {
const root = runtime.el;
if (!root) return;
const panel = root.querySelector(".iwb-editor-export-settings");
const toggle = root.querySelector('[data-action="toggleExportSettings"]');
if (panel && panel.dataset.bound === "1") return;
if (panel) panel.dataset.bound = "1";
if (toggle && panel) {
toggle.addEventListener("mousedown", (e) => e.stopPropagation());
toggle.addEventListener("click", (e) => {
e.stopPropagation();
const open2 = panel.classList.toggle("open");
toggle.setAttribute("aria-expanded", String(open2));
});
}
if (panel) {
panel.addEventListener("mousedown", (e) => e.stopPropagation());
panel.addEventListener("click", (e) => {
const btn = e.target.closest("[data-export-key]");
if (!btn) return;
e.stopPropagation();
let v = btn.dataset.exportValue;
if (btn.dataset.exportKey === "maxKB" || btn.dataset.exportKey === "size") v = Number(v);
setExportOption(btn.dataset.exportKey, v);
});
}
}
function buildOutputCanvas() {
const o = S.exportOptions || DEFAULT_EXPORT;
const white = effectiveBg(o) === "white";
const src = getCompositeCanvas();
let out = src;
if (o.preset === "ecom800") {
const size = o.size;
const c = document.createElement("canvas");
c.width = size;
c.height = size;
const cx = c.getContext("2d");
if (white) {
cx.fillStyle = "#ffffff";
cx.fillRect(0, 0, size, size);
}
const long = Math.max(S.imgW, S.imgH) || 1;
const k = size * 0.8 / long;
const w = S.imgW * k, h = S.imgH * k;
cx.drawImage(src, (size - w) / 2, (size - h) / 2, w, h);
src.width = 0;
src.height = 0;
out = c;
} else if (white) {
const c = document.createElement("canvas");
c.width = S.imgW;
c.height = S.imgH;
const cx = c.getContext("2d");
cx.fillStyle = "#ffffff";
cx.fillRect(0, 0, c.width, c.height);
cx.drawImage(src, 0, 0);
src.width = 0;
src.height = 0;
out = c;
}
return out;
}
function toBlob(canvas, mime, quality) {
return new Promise((resolve, reject) => {
try {
if (typeof canvas.toBlob !== "function") {
reject(new Error("当前环境不支持 toBlob"));
return;
}
canvas.toBlob((blob) => {
if (blob) resolve(blob);
else {
try {
resolve(dataUrlToBlob2(canvas.toDataURL(mime, quality)));
} catch (e) {
reject(e);
}
}
}, mime, quality);
} catch (e) {
reject(e);
}
});
}
function dataUrlToBlob2(dataUrl) {
const comma = dataUrl.indexOf(",");
const meta = dataUrl.slice(0, comma);
const bin = atob(dataUrl.slice(comma + 1));
const bytes = new Uint8Array(bin.length);
for (let i = 0; i < bin.length; i++) bytes[i] = bin.charCodeAt(i);
return new Blob([bytes], { type: (/^data:([^;,]+)/.exec(meta) || [])[1] || "image/png" });
}
async function encodeOutput(canvas) {
const o = S.exportOptions || DEFAULT_EXPORT;
const mime = o.format === "jpeg" ? "image/jpeg" : o.format === "webp" ? "image/webp" : "image/png";
const limit = o.preset === "ecom800" && o.maxKB > 0 ? o.maxKB * 1024 : 0;
let blob = await toBlob(canvas, mime, 0.92);
if (limit && blob.size > limit) {
if (o.format === "png") {
toast("PNG 无法降质:当前 " + Math.round(blob.size / 1024) + "KB,可切换 JPG/WebP 或缩小尺寸", "warn");
} else {
let q = 0.82;
for (let i = 0; i < 8 && blob.size > limit && q >= 0.3; i++) {
blob = await toBlob(canvas, mime, q);
q -= 0.09;
}
if (blob.size > limit) toast("已尽力压缩,仍为 " + Math.round(blob.size / 1024) + "KB(目标 ≤" + o.maxKB + "KB)", "warn");
}
}
return blob;
}
async function prepareOutput() {
const canvas = buildOutputCanvas();
try {
const blob = await encodeOutput(canvas);
const o = S.exportOptions || DEFAULT_EXPORT;
const info = {
bytes: blob.size,
width: canvas.width,
height: canvas.height,
format: o.format,
bg: effectiveBg(o),
preset: o.preset,
maxKB: o.preset === "ecom800" ? o.maxKB : 0,
// 记下产出时用的设置指纹,UI 才能判断「上次输出」是否还代表当前设置
signature: exportSignature(o)
};
S.lastExport = info;
return { blob, info };
} finally {
canvas.width = 0;
canvas.height = 0;
}
}
function downloadBlob(blob) {
const o = S.exportOptions || DEFAULT_EXPORT;
const ext = o.format === "jpeg" ? "jpg" : o.format;
const raw = S.callbacks && S.callbacks.imageName || "image.png";
const name = String(raw).replace(/\.[^.]+$/, "") + "_edit." + ext;
const url = URL.createObjectURL(blob);
const a = document.createElement("a");
a.href = url;
a.download = name;
document.body.appendChild(a);
a.click();
if (a.parentNode) a.parentNode.removeChild(a);
setTimeout(() => {
try {
URL.revokeObjectURL(url);
} catch (e) {
}
}, 2e3);
toast("已下载 " + name + "(" + Math.round(blob.size / 1024) + "KB)", "success");
}
async function toPngBlob(blob) {
try {
if (typeof createImageBitmap === "function") {
const bmp = await createImageBitmap(blob);
const c = document.createElement("canvas");
c.width = bmp.width;
c.height = bmp.height;
c.getContext("2d").drawImage(bmp, 0, 0);
if (typeof bmp.close === "function") bmp.close();
const out = await new Promise((res) => c.toBlob((b) => res(b), "image/png"));
c.width = 0;
c.height = 0;
if (out) return out;
}
} catch (e) {
}
return await new Promise((resolve) => {
const url = URL.createObjectURL(blob);
const img = new Image();
img.onload = () => {
const c = document.createElement("canvas");
c.width = img.naturalWidth;
c.height = img.naturalHeight;
c.getContext("2d").drawImage(img, 0, 0);
try {
URL.revokeObjectURL(url);
} catch (e) {
}
c.toBlob((b) => resolve(b || blob), "image/png");
};
img.onerror = () => {
try {
URL.revokeObjectURL(url);
} catch (e) {
}
resolve(blob);
};
img.src = url;
});
}
async function copyBlobToClipboard(blob) {
const nav = typeof navigator !== "undefined" ? navigator : null;
const CI = typeof window !== "undefined" ? window.ClipboardItem : null;
if (!nav || !nav.clipboard || typeof nav.clipboard.write !== "function" || typeof CI !== "function") {
toast("当前浏览器不支持复制图片,请用「导出」下载", "warn");
return false;
}
let png = blob;
if (blob.type !== "image/png") {
try {
png = await toPngBlob(blob);
} catch (e) {
png = blob;
}
}
try {
await nav.clipboard.write([new CI({ "image/png": png })]);
toast("已复制到剪贴板(" + Math.round(png.size / 1024) + "KB),可直接粘贴", "success");
return true;
} catch (e) {
toast("复制失败:" + (e && e.message || "浏览器拒绝了剪贴板写入") + ";可用「导出」下载", "error");
return false;
}
}
// image-annotate/plugin/editor/index.js
async function open(options) {
if (!options || !options.imageBase64) return;
createEl();
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;
S.imgH = img.naturalHeight || img.height;
S.originalImage = img;
runtime.el.style.display = "flex";
S.open = true;
S.zoom = 1;
setupCanvas(img);
resetState();
updateAllUI();
registerSelectionCommands();
loadExportOptions();
loadRecentColors();
bindLiteUI();
bindFloating();
bindExportUI();
initPanels();
renderAll();
} catch (e) {
console.error("[IWB编辑器] 打开失败:", e);
if (runtime.el) runtime.el.style.display = "none";
if (options.onError) options.onError(e.message);
} finally {
options.imageBase64 = null;
}
}
function resetState() {
purgeVectorCanvases();
S.history = [];
S.redoStack = [];
S.cropRect = null;
S.cropHandle = null;
S.cropMoving = false;
S.moveStart = null;
S.isDrawing = false;
S.panning = false;
S.tool = "brush";
S.color = "#ff4444";
S.brushSize = 3;
S.brushHardness = 100;
S.brushOpacity = 1;
S.prevTool = null;
S.pickerComposite = null;
S.rectFill = false;
S.shapeLineWidth = 3;
S.textSize = 32;
S.cropConstraint = { type: "free", ratio: 0, sizeW: 0, sizeH: 0 };
S.textLayers = [];
S.selectedTextId = null;
S.textDrag = null;
S.textEditingId = null;
S.shapeLayers = [];
S.selectedShapeId = null;
S.shapeDrag = null;
S.penPath = null;
S.penEditId = null;
S.penDragPt = -1;
S.penDragBase = null;
S.penDragPending = null;
S.selectedLayerId = null;
S.bitmapDrag = null;
S.layerMulti.length = 0;
S.hoverPos = null;
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;
S.placingStart = null;
const sizeToggle = runtime.el && runtime.el.querySelector(".iwb-editor-size-toggle");
if (sizeToggle) {
sizeToggle.classList.remove("active");
sizeToggle.setAttribute("aria-pressed", "false");
sizeToggle.textContent = "启用尺寸";
}
S.selection = null;
S.marquee = null;
S.lassoPts = null;
S.interaction = "idle";
S.lastExport = null;
if (S._antFrame) {
cancelAnimationFrame(S._antFrame);
S._antFrame = 0;
}
hideSelectionContext();
if (S.selectionCtx) renderSelection();
if (S.cursorCtx) {
S.cursorCtx.setTransform(1, 0, 0, 1, 0, 0);
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();
renderSelection();
syncAnts();
positionFloating();
}
function initPanels() {
if (!runtime.el) return;
const st = S.callbacks && S.callbacks.settings;
let saved = false;
if (st && typeof st.get === "function") {
try {
saved = !!st.get("panelsCollapsed");
} catch (e) {
}
}
const auto = (window.innerWidth || 1440) < 1100;
runtime.el.classList.toggle("panels-collapsed", saved || auto);
}
function close(reason) {
const callbacks = S.callbacks;
try {
if (callbacks && typeof callbacks.onClose === "function") callbacks.onClose(reason || "cancel");
} catch (e) {
console.error("[IWB编辑器] onClose 回调异常:", e);
}
if (runtime.el) {
hideTextInput();
runtime.el.style.display = "none";
}
releaseEditorMemory();
S.open = false;
S.callbacks = null;
S.placingImage = null;
S.placingHandle = null;
S.placingStart = null;
S.penPath = null;
S.textEditingId = null;
clearSelection();
hideSelectionContext();
disposeSelection();
}
function releaseEditorMemory() {
S.history = [];
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;
S.penDragPending = null;
S.placingImage = null;
S.placingHandle = null;
S.placingStart = null;
for (const layer of S.layers) {
try {
if (layer.sourceCanvas) {
layer.sourceCanvas.width = 0;
layer.sourceCanvas.height = 0;
}
if (layer.canvas) {
if (layer.canvas.parentNode) layer.canvas.parentNode.removeChild(layer.canvas);
layer.canvas.width = 0;
layer.canvas.height = 0;
}
} catch (e) {
}
}
S.layers = [];
for (const c of [S.textCanvas, S.strokeCanvas, S.overlayCanvas, S.selectionCanvas, S.cursorCanvas]) {
try {
if (c) {
c.width = 0;
c.height = 0;
}
} catch (e) {
}
}
purgeVectorCanvases();
}
async function exportResult(mode) {
if (S.placingImage) cancelImagePlacement();
try {
const { blob } = await prepareOutput();
if (mode === "download") {
downloadBlob(blob);
if (S.renderAll) S.renderAll();
return;
}
if (S.callbacks && S.callbacks.onResult) S.callbacks.onResult(blob, mode);
close("done");
} catch (e) {
console.error("[IWB编辑器] 导出失败:", e);
toast("导出失败:" + (e && e.message || "图片可能跨域"), "error");
if (S.callbacks && S.callbacks.onError) S.callbacks.onError("导出失败:" + (e && e.message || "图片跨域"));
}
}
async function copyResult() {
if (S.placingImage) cancelImagePlacement();
try {
const { blob } = await prepareOutput();
await copyBlobToClipboard(blob);
if (S.renderAll) S.renderAll();
} catch (e) {
console.error("[IWB编辑器] 复制失败:", e);
toast("复制失败:" + (e && e.message || "图片可能跨域"), "error");
}
}
var __stats = () => ({
history: S.history.length,
historyBytes: S.history.reduce((n, s) => n + (s.__bytes || 0), 0),
redo: S.redoStack.length,
redoBytes: S.redoStack.reduce((n, s) => n + (s.__bytes || 0), 0),
maxEntries: HISTORY_MAX_ENTRIES,
maxBytes: HISTORY_MAX_BYTES,
historyBudget: historyBudgetBytes(),
...snapshotStats
});
var __debug = () => ({
open: S.open,
tool: S.tool,
color: S.color,
altPicker: !!S.altPicker,
doc: { w: S.imgW, h: S.imgH },
zoom: S.zoom,
fit: { w: Math.round(S.fitW || 0), h: Math.round(S.fitH || 0) },
layers: S.layers.map((l) => ({
id: l.id,
name: l.name,
z: l.z,
locked: !!l.locked,
visible: l.visible !== false,
// 不透明度有两个面:数据字段(导出/合并用)与 CSS(屏幕上看到的),两者必须一致
opacity: l.opacity == null ? 1 : l.opacity,
cssOpacity: l.canvas ? parseFloat(l.canvas.style.opacity || "1") : null
})),
shapes: S.shapeLayers.map((s) => ({ id: s.id, type: s.type, lw: s.lw, fill: !!s.fill, closed: !!s.closed, z: s.z, color: s.color, radius: s.radius || 0, x1: Math.round(s.x1 || 0), y1: Math.round(s.y1 || 0), x2: Math.round(s.x2 || 0), y2: Math.round(s.y2 || 0) })),
texts: S.textLayers.map((t) => ({
id: t.id,
text: t.text,
x: t.x,
y: t.y,
fontSize: t.fontSize,
color: t.color,
fontWeight: t.fontWeight,
align: t.align,
lineHeight: t.lineHeight,
strokeWidth: t.strokeWidth,
strokeColor: t.strokeColor,
bgFill: !!t.bgFill,
bgColor: t.bgColor,
// 包围盒:吸附/多行/底色/描边的断言都靠它,和绘制共用同一套度量
box: (() => {
const b = textBounds(t);
return { x: Math.round(b.x), y: Math.round(b.y), w: Math.round(b.w), h: Math.round(b.h) };
})()
})),
// 吸附参考线(拖动中才有)与最近使用颜色:交互回归用
guides: S.guides ? S.guides.map((g) => ({ axis: g.axis, at: Math.round(g.at * 10) / 10 })) : [],
recentColors: (S.recentColors || []).slice(),
textDefaults: {
weight: S.textWeight,
align: S.textAlign,
lineHeight: S.textLineHeight,
strokeWidth: S.textStrokeWidth,
strokeColor: S.textStrokeColor,
bgFill: S.textBgFill,
bgColor: S.textBgColor
},
selectedShapeId: S.selectedShapeId,
// 光标所在的图片坐标(状态栏同源):换算问题的第一现场证据
lastPos: S.lastPos ? { x: Math.round(S.lastPos.x), y: Math.round(S.lastPos.y) } : null,
// 当前正在进行的拖拽类型:move 才是拖动本体,handle/rotate 说明点到了控制点
drag: S.shapeDrag ? "shape:" + S.shapeDrag.mode + (S.shapeDrag.handle ? ":" + S.shapeDrag.handle : "") : S.textDrag ? "text:" + S.textDrag.mode : S.bitmapDrag ? "bitmap:" + S.bitmapDrag.mode + (S.bitmapDrag.handle ? ":" + S.bitmapDrag.handle : "") : null,
selectedTextId: S.selectedTextId,
penEditId: S.penEditId,
activeLayerId: S.activeLayerId,
selectedLayerId: S.selectedLayerId,
layerMulti: S.layerMulti.map((x) => x.type + ":" + x.id),
selection: selectionInfo(),
toolOptions: {
brushSize: S.brushSize,
brushHardness: S.brushHardness,
brushOpacity: S.brushOpacity,
shapeLineWidth: S.shapeLineWidth,
textSize: S.textSize,
rectFill: S.rectFill,
penFill: S.penFill
},
history: S.history.length,
historyLabels: S.history.map((s) => s.__label || ""),
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;
try {
return Array.from(l.ctx.getImageData(Math.round(x), Math.round(y), 1, 1).data);
} catch (e) {
return null;
}
},
// 区域透明像素统计:断言「合并后两半都有内容」比逐点采样快一个量级
alphaIn: (id, x0, y0, x1, y1) => {
const l = S.layers.find((v) => v.id === id);
if (!l || !l.ctx) return 0;
try {
const w = Math.max(1, Math.round(x1 - x0));
const h = Math.max(1, Math.round(y1 - y0));
const d = l.ctx.getImageData(Math.round(x0), Math.round(y0), w, h).data;
let n = 0;
for (let i = 3; i < d.length; i += 4) if (d[i] > 0) n++;
return n;
} catch (e) {
return 0;
}
}
});
window.__iwbEditor = {
open,
close,
__stats,
__debug
};
// 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-editor-tools .iwb-editor-action[data-action="redo"] { right: 118px; }\n.iwb-editor-header > .iwb-editor-tools .iwb-editor-action[data-action="reset"] { right: 82px; }\n.iwb-editor-header > .iwb-editor-tools .iwb-editor-action[data-action="restore"] { right: 46px; }\n.iwb-editor-header > .iwb-editor-tools .iwb-editor-divider {\n width: 24px;\n height: 1px;\n margin: 4px 0;\n}\n\n.iwb-editor-title {\n color: #cdd6f4;\n font-size: 14px;\n font-weight: 600;\n white-space: nowrap;\n}\n\n.iwb-editor-tools {\n display: flex;\n align-items: center;\n gap: 4px;\n}\n\n.iwb-editor-tool, .iwb-editor-action {\n background: #313244;\n border: none;\n border-radius: 6px;\n color: #cdd6f4;\n width: 32px; height: 32px;\n display: flex;\n align-items: center;\n justify-content: center;\n cursor: pointer;\n font-size: 15px;\n transition: background 0.15s, transform 0.1s;\n}\n.iwb-editor-tool:hover, .iwb-editor-action:hover { background: #45475a; transform: scale(1.08); }\n.iwb-editor-tool.active { background: #e8a735; color: #1e1e2e; }\n.iwb-editor-tool svg, .iwb-editor-action svg { display: block; }\n.iwb-editor-layer-btn svg { display: block; }\n\n/* 复原按钮:绿色高亮,与撤销/重做/清空区分 */\n.iwb-editor-action-restore { background: #1a7f37; color: #fff; }\n.iwb-editor-action-restore:hover { background: #15803d !important; }\n\n.iwb-editor-divider {\n width: 1px; height: 20px;\n background: #45475a;\n margin: 0 4px;\n}\n\n.iwb-editor-params {\n display: flex;\n align-items: center;\n gap: 10px;\n margin-left: 12px;\n justify-content: flex-start;\n min-width: 0;\n flex: 1 1 auto;\n flex-wrap: wrap;\n}\n.iwb-editor-params .iwb-editor-zoom { margin-left: auto; order: 20; }\n.iwb-editor-top-colors { display: none; }\n\n.iwb-editor-colors { display: flex; gap: 4px; }\n.iwb-editor-color {\n width: 20px; height: 20px;\n border-radius: 50%;\n cursor: pointer;\n border: 2px solid transparent;\n transition: transform 0.1s, border-color 0.15s;\n}\n.iwb-editor-color:hover { transform: scale(1.2); }\n.iwb-editor-color.active { border-color: #fff; transform: scale(1.15); }\n\n.iwb-editor-brush-label {\n display: flex;\n align-items: center;\n gap: 6px;\n color: #a6adc8;\n font-size: 12px;\n}\n.iwb-editor-brush-size { width: 80px; cursor: pointer; }\n.iwb-editor-brush-val { color: #e8a735; font-weight: 600; min-width: 16px; }\n\n/* 笔刷/橡皮大小精确数值输入框 */\n.iwb-editor-brush-num,\n.iwb-editor-eraser-num {\n width: 44px;\n padding: 2px 3px;\n background: #313244;\n border: 1px solid #45475a;\n border-radius: 5px;\n color: #e8a735;\n font-weight: 600;\n font-size: 11px;\n font-family: inherit;\n text-align: center;\n}\n.iwb-editor-brush-num:focus,\n.iwb-editor-eraser-num:focus {\n outline: none;\n border-color: #e8a735;\n background: #1e1e2e;\n}\n.iwb-editor-brush-num::-webkit-outer-spin-button,\n.iwb-editor-brush-num::-webkit-inner-spin-button,\n.iwb-editor-eraser-num::-webkit-outer-spin-button,\n.iwb-editor-eraser-num::-webkit-inner-spin-button {\n -webkit-appearance: none; /* 去掉上下箭头,窄输入框更干净 */\n margin: 0;\n}\n\n/* 实心矩形开关 */\n.iwb-editor-fill-btn {\n background: #313244;\n border: 1px solid #45475a;\n border-radius: 6px;\n color: #a6adc8;\n padding: 4px 10px;\n font-size: 12px;\n cursor: pointer;\n transition: background 0.15s, color 0.15s, border-color 0.15s;\n white-space: nowrap;\n}\n.iwb-editor-fill-btn:hover { background: #45475a; }\n.iwb-editor-fill-btn.active {\n background: #e8a735;\n border-color: #e8a735;\n color: #1e1e2e;\n font-weight: 600;\n}\n\n/* 画笔参数组(硬度/透明度,画笔与橡皮工具共用) */\n.iwb-editor-brush-group {\n display: flex;\n align-items: center;\n gap: 10px;\n}\n.iwb-editor-layer-group {\n display: flex;\n align-items: center;\n gap: 3px;\n}\n.iwb-editor-layer-btn {\n background: #313244;\n border: 1px solid #45475a;\n border-radius: 6px;\n color: #a6adc8;\n width: 26px;\n height: 26px;\n font-size: 14px;\n line-height: 1;\n cursor: pointer;\n display: inline-flex;\n align-items: center;\n justify-content: center;\n transition: background 0.15s, color 0.15s, border-color 0.15s, opacity 0.15s;\n}\n.iwb-editor-layer-btn:hover:not(:disabled) { background: #45475a; color: #cdd6f4; }\n.iwb-editor-layer-btn:disabled {\n opacity: 0.35;\n cursor: not-allowed;\n}\n\n/* 缩放控件 */\n.iwb-editor-zoom {\n display: flex;\n align-items: center;\n gap: 2px;\n background: #313244;\n border-radius: 6px;\n padding: 2px;\n}\n.iwb-editor-zoom-btn {\n background: transparent;\n border: none;\n color: #cdd6f4;\n width: 26px;\n height: 26px;\n border-radius: 4px;\n cursor: pointer;\n font-size: 14px;\n line-height: 1;\n display: flex;\n align-items: center;\n justify-content: center;\n transition: background 0.15s;\n}\n.iwb-editor-zoom-btn:hover { background: #45475a; }\n.iwb-editor-zoom-btn:active { transform: scale(0.94); }\n.iwb-editor-zoom-fit { font-size: 12px; width: auto; padding: 0 8px; }\n.iwb-editor-zoom-val {\n color: #e8a735;\n font-size: 12px;\n font-weight: 600;\n min-width: 46px;\n text-align: center;\n font-variant-numeric: tabular-nums;\n user-select: none;\n}\n\n/* 底部操作提示 */\n.iwb-editor-zoom-hint {\n position: absolute;\n bottom: 8px;\n right: 14px;\n color: #7f849c;\n font-size: 11px;\n background: rgba(24, 24, 37, 0.85);\n padding: 3px 10px;\n border-radius: 4px;\n pointer-events: none;\n z-index: 5;\n}\n\n.iwb-editor-canvas-wrap {\n position: relative;\n background: #11111b;\n flex: 1 1 auto;\n min-height: 0;\n max-width: 100%;\n max-height: 100%;\n overflow: hidden; /* 裁剪框允许显示在图片边界外;编辑区仍由模态层裁切 */\n overflow: clip; /* v1.2.8:hidden 仍可被编程滚动(点击底部工具栏会触发 scrollIntoView 把画布滚跑),clip 彻底禁止滚动 */\n padding: 12px;\n}\n\n.iwb-editor-canvas-stack {\n position: absolute;\n left: 0;\n top: 0;\n display: block;\n width: 0;\n height: 0;\n /* 仅图片工作区显示透明棋盘格,外围裁剪工作区保持纯色。 */\n background-color: #d6d6d6;\n background-image:\n linear-gradient(45deg, #b8b8b8 25%, transparent 25%),\n linear-gradient(-45deg, #b8b8b8 25%, transparent 25%),\n linear-gradient(45deg, transparent 75%, #b8b8b8 75%),\n linear-gradient(-45deg, transparent 75%, #b8b8b8 75%);\n background-size: 20px 20px;\n background-position: 0 0, 0 10px, 10px -10px, -10px 0;\n}\n\n.iwb-editor-base, .iwb-editor-draw, .iwb-editor-text, .iwb-editor-crop-overlay {\n display: block;\n}\n/* 位图图层 canvas(动态创建) */\n.iwb-editor-layer-canvas {\n display: block;\n position: absolute;\n top: 0; left: 0;\n}\n.iwb-editor-base {\n background: #fff;\n /* 棋盘格透明背景示意 */\n background-image:\n linear-gradient(45deg, #e0e0e0 25%, transparent 25%),\n linear-gradient(-45deg, #e0e0e0 25%, transparent 25%),\n linear-gradient(45deg, transparent 75%, #e0e0e0 75%),\n linear-gradient(-45deg, transparent 75%, #e0e0e0 75%);\n background-size: 20px 20px;\n background-position: 0 0, 0 10px, 10px -10px, -10px 0px;\n}\n.iwb-editor-draw {\n position: absolute;\n top: 0; left: 0;\n cursor: crosshair;\n}\n\n/* 笔划预览层:一笔进行中显示(draw 之上、text 之下),事件穿透 */\n.iwb-editor-stroke {\n position: absolute;\n top: 0; left: 0;\n pointer-events: none;\n display: none;\n}\n\n.iwb-editor-brush-hardness { width: 70px; cursor: pointer; }\n.iwb-editor-brush-hardness-val { color: #e8a735; font-weight: 600; min-width: 20px; display: inline-block; text-align: right; }\n.iwb-editor-brush-opacity { width: 70px; cursor: pointer; }\n.iwb-editor-brush-opacity-val { color: #e8a735; font-weight: 600; min-width: 34px; display: inline-block; text-align: right; }\n\n/* 自定义颜色(原生取色器伪装成圆形色板) */\n.iwb-editor-color-custom {\n position: relative;\n overflow: hidden;\n border: 2px dashed #a6adc8;\n}\n.iwb-editor-color-custom.active { border-color: #fff; border-style: solid; transform: scale(1.15); }\n.iwb-editor-color-custom input[type="color"] {\n position: absolute;\n inset: -6px;\n width: calc(100% + 12px);\n height: calc(100% + 12px);\n padding: 0;\n border: none;\n cursor: pointer;\n background: conic-gradient(#ff4444, #ffaa00, #44dd44, #4488ff, #aa44ff, #ff4444);\n}\n.iwb-editor-color-custom input[type="color"]::-webkit-color-swatch-wrapper { padding: 0; }\n.iwb-editor-color-custom input[type="color"]::-webkit-color-swatch { border: none; }\n\n/* 吸管悬停预览浮窗 */\n.iwb-editor-picker-tip {\n position: fixed;\n z-index: 2147483000;\n display: none;\n align-items: center;\n gap: 6px;\n background: rgba(30, 30, 46, 0.95);\n border: 1px solid rgba(255, 255, 255, 0.14);\n border-radius: 6px;\n padding: 4px 8px;\n pointer-events: none;\n font-family: system-ui, -apple-system, "Segoe UI", sans-serif;\n}\n.iwb-editor-picker-chip {\n width: 16px;\n height: 16px;\n border-radius: 4px;\n background: transparent;\n}\n.iwb-editor-picker-hex {\n color: #cdd6f4;\n font-size: 12px;\n font-weight: 600;\n font-variant-numeric: tabular-nums;\n}\n\n/* 文字图层:独立 canvas,事件穿透到下层 drawCanvas */\n.iwb-editor-text {\n position: absolute;\n top: 0; left: 0;\n pointer-events: none;\n}\n\n/* 裁剪覆盖层:遮罩/选区框/手柄画在这层,不污染标注层 */\n.iwb-editor-crop-overlay {\n position: absolute;\n top: 0; left: 0;\n pointer-events: none;\n}\n\n/* 文字输入框 */\n.iwb-editor-text-input {\n position: absolute;\n display: none;\n padding: 4px 8px;\n border: 2px solid #4488ff;\n border-radius: 4px;\n font-size: 14px;\n line-height: 1.35;\n /* textarea:默认会显示右下角拖拽柄与滚动条,画布上的就地输入框都不要 */\n resize: none;\n overflow: hidden;\n white-space: pre;\n background: rgba(255, 255, 255, 0.95);\n color: #1e1e2e;\n z-index: 10;\n min-width: 120px;\n min-height: 30px;\n font-family: inherit;\n}\n.iwb-editor-text-input:focus { outline: none; box-shadow: 0 0 0 3px rgba(68, 136, 255, 0.3); }\n\n/* 裁剪确认栏(含约束控件) */\n.iwb-editor-crop-bar {\n position: absolute;\n bottom: 16px;\n left: 50%;\n transform: translateX(-50%);\n display: none;\n gap: 8px;\n z-index: 10;\n align-items: center;\n background: rgba(24, 24, 37, 0.92);\n border: 1px solid #313244;\n border-radius: 8px;\n padding: 6px 10px;\n box-shadow: 0 4px 16px rgba(0, 0, 0, 0.4);\n flex-wrap: wrap;\n max-width: 90%;\n justify-content: center;\n}\n\n.iwb-editor-constraint-group {\n display: flex;\n align-items: center;\n gap: 4px;\n}\n\n.iwb-editor-constraint-label {\n color: #7f849c;\n font-size: 11px;\n margin-right: 2px;\n white-space: nowrap;\n}\n\n.iwb-editor-constraint-btn {\n background: #313244;\n border: none;\n border-radius: 4px;\n color: #cdd6f4;\n padding: 3px 8px;\n font-size: 12px;\n cursor: pointer;\n transition: background 0.15s, transform 0.1s;\n white-space: nowrap;\n}\n.iwb-editor-constraint-btn:hover { background: #45475a; transform: scale(1.05); }\n.iwb-editor-constraint-btn.active { background: #4488ff; color: #fff; }\n\n.iwb-editor-constraint-sep {\n width: 1px;\n height: 20px;\n background: #45475a;\n}\n\n.iwb-editor-size-input {\n width: 50px;\n background: #313244;\n border: 1px solid #45475a;\n border-radius: 4px;\n color: #cdd6f4;\n padding: 3px 6px;\n font-size: 12px;\n text-align: center;\n}\n.iwb-editor-size-input:focus { outline: none; border-color: #4488ff; }\n.iwb-editor-size-input::-webkit-inner-spin-button { -webkit-appearance: none; }\n\n.iwb-editor-size-x { color: #7f849c; font-size: 12px; }\n\n.iwb-editor-size-apply {\n background: #313244;\n border: 1px solid #4488ff;\n color: #4488ff;\n border-radius: 4px;\n padding: 3px 8px;\n font-size: 12px;\n cursor: pointer;\n transition: background 0.15s;\n}\n.iwb-editor-size-apply:hover { background: #4488ff; color: #fff; }\n\n.iwb-editor-crop-info {\n color: #e8a735;\n font-size: 12px;\n font-weight: 600;\n font-variant-numeric: tabular-nums;\n white-space: nowrap;\n min-width: 60px;\n text-align: center;\n}\n\n.iwb-editor-crop-confirm, .iwb-editor-crop-cancel {\n padding: 6px 16px;\n border: none;\n border-radius: 6px;\n font-size: 13px;\n font-weight: 500;\n cursor: pointer;\n}\n.iwb-editor-crop-confirm { background: #1a7f37; color: #fff; }\n.iwb-editor-crop-confirm:hover { background: #15803d; }\n.iwb-editor-crop-cancel { background: #cf222e; color: #fff; }\n.iwb-editor-crop-cancel:hover { background: #b91c1c; }\n\n/* 底部 */\n.iwb-editor-footer {\n display: flex;\n justify-content: flex-end;\n gap: 8px;\n padding: 12px 16px;\n background: #181825;\n border-top: 1px solid #313244;\n}\n\n.iwb-editor-btn {\n padding: 8px 20px;\n border: none;\n border-radius: 6px;\n font-size: 13px;\n font-weight: 500;\n cursor: pointer;\n transition: background 0.15s, transform 0.1s;\n}\n.iwb-editor-btn:hover { transform: scale(1.03); }\n.iwb-editor-btn-cancel { background: #45475a; color: #cdd6f4; }\n.iwb-editor-btn-cancel:hover { background: #585b70; }\n.iwb-editor-btn-new { background: #4488ff; color: #fff; }\n.iwb-editor-btn-new:hover { background: #3578f0; }\n.iwb-editor-btn-replace { background: #e8a735; color: #1e1e2e; }\n.iwb-editor-btn-replace:hover { background: #d49628; }\n\n/* ==================== 图层面板 ==================== */\n\n.iwb-editor-layer-panel {\n width: 290px;\n min-width: 290px;\n background: #181825;\n border-left: 1px solid #313244;\n display: flex;\n flex-direction: column;\n overflow: hidden;\n}\n\n.iwb-editor-layer-panel-header {\n display: flex;\n align-items: center;\n justify-content: space-between;\n padding: 10px 12px;\n border-bottom: 1px solid #313244;\n}\n\n.iwb-editor-layer-panel-title {\n color: #cdd6f4;\n font-size: 13px;\n font-weight: 600;\n}\n\n.iwb-editor-layer-add-group {\n display: flex;\n gap: 4px;\n}\n\n.iwb-editor-layer-add-btn {\n background: #313244;\n border: 1px solid #45475a;\n border-radius: 6px;\n color: #cdd6f4;\n width: 26px;\n height: 26px;\n cursor: pointer;\n display: flex;\n align-items: center;\n justify-content: center;\n transition: background 0.15s;\n}\n.iwb-editor-layer-add-btn:hover { background: #45475a; color: #e8a735; }\n.iwb-editor-layer-add-btn svg { display: block; }\n\n.iwb-editor-layer-list {\n flex: 1 1 auto;\n overflow-y: auto;\n padding: 4px;\n /* 拖动排序的插入线是绝对定位的,锚点必须在列表上(随滚动一起移动) */\n position: relative;\n}\n\n/* 图层项:整项改成「行 + 可选的不透明度行」,两行都靠 .iwb-layer-row 保持原来的横向排布 */\n.iwb-layer-item {\n display: block;\n padding: 5px 8px;\n border-radius: 6px;\n cursor: grab;\n user-select: none;\n transition: background 0.12s;\n margin-bottom: 2px;\n}\n.iwb-layer-row {\n display: flex;\n align-items: center;\n gap: 6px;\n min-width: 0;\n}\n.iwb-layer-item:hover { background: #313244; }\n.iwb-layer-item.active {\n background: #313244;\n box-shadow: inset 2px 0 0 #e8a735;\n}\n.iwb-layer-item.hidden { opacity: 0.5; }\n/* 拖动中:整行跟着指针浮起,压住相邻行;其余行由 JS 实时让位(落点反馈) */\n.iwb-layer-item.dragging {\n position: relative;\n z-index: 3;\n opacity: 1;\n background: #3a3d55;\n box-shadow: 0 6px 18px rgba(0, 0, 0, 0.5), inset 0 0 0 1px #e8a735;\n transition: none;\n cursor: grabbing;\n}\n.iwb-editor-layer-list.sorting,\n.iwb-editor-layer-list.sorting .iwb-layer-item { cursor: grabbing; }\n/* 画笔/橡皮作用目标:与「选中」分离,避免出现两个图层同时高亮 */\n.iwb-layer-paint { flex: 0 0 auto; color: #a6adc8; font-size: 11px; opacity: 0.85; }\n/* 不透明度角标:只有非 100% 才出现,一眼看出哪层被调淡了 */\n.iwb-layer-op { flex: 0 0 auto; font-size: 10px; color: #a6adc8; font-variant-numeric: tabular-nums; }\n\n/* 缩略图:canvas 画内容,类型图标垫在下面当兜底(空图层的缩略图是全透明的) */\n.iwb-layer-thumb {\n position: relative;\n flex: 0 0 auto;\n width: 22px;\n height: 22px;\n border-radius: 3px;\n overflow: hidden;\n background-color: #1e1e2e;\n background-image: linear-gradient(45deg, #33334a 25%, transparent 25%), linear-gradient(-45deg, #33334a 25%, transparent 25%), linear-gradient(45deg, transparent 75%, #33334a 75%), linear-gradient(-45deg, transparent 75%, #33334a 75%);\n background-size: 8px 8px;\n background-position: 0 0, 0 4px, 4px -4px, -4px 0;\n box-shadow: inset 0 0 0 1px #45475a;\n}\n.iwb-layer-thumb canvas { position: absolute; inset: 0; width: 100%; height: 100%; display: block; }\n.iwb-layer-thumb .iwb-layer-icon {\n position: absolute;\n inset: 0;\n width: 100%;\n display: flex;\n align-items: center;\n justify-content: center;\n color: #7f849c;\n}\n\n/* 不透明度行:只出现在选中项下,拖动时不能被重绘打断 */\n.iwb-layer-op-row {\n display: flex;\n align-items: center;\n gap: 6px;\n margin: 4px 0 1px 26px;\n}\n.iwb-layer-opacity {\n flex: 1 1 auto;\n min-width: 0;\n height: 14px;\n accent-color: #e8a735;\n cursor: pointer;\n}\n.iwb-layer-op-val {\n flex: 0 0 auto;\n width: 32px;\n text-align: right;\n font-size: 10px;\n color: #a6adc8;\n font-variant-numeric: tabular-nums;\n}\n\n/* 可重命名的图层名:悬停给个提示,进入编辑时换成输入框 */\n.iwb-layer-name.renamable:hover { color: #e8a735; }\n.iwb-layer-name-input {\n flex: 1 1 auto;\n min-width: 0;\n padding: 1px 4px;\n border: 1px solid #e8a735;\n border-radius: 3px;\n background: #1e1e2e;\n color: #cdd6f4;\n font-size: 12px;\n font-family: inherit;\n outline: none;\n}\n\n.iwb-layer-vis {\n background: none;\n border: none;\n color: #a6adc8;\n cursor: pointer;\n font-size: 13px;\n width: 20px;\n height: 20px;\n display: flex;\n align-items: center;\n justify-content: center;\n border-radius: 4px;\n transition: background 0.12s;\n}\n.iwb-layer-vis:hover { background: #45475a; }\n\n.iwb-layer-icon {\n font-size: 13px;\n width: 18px;\n text-align: center;\n flex-shrink: 0;\n}\n\n.iwb-layer-name {\n color: #cdd6f4;\n font-size: 12px;\n flex: 1 1 auto;\n white-space: nowrap;\n overflow: hidden;\n text-overflow: ellipsis;\n min-width: 0;\n}\n\n.iwb-layer-lock {\n background: none;\n border: none;\n color: #7f849c;\n cursor: pointer;\n width: 20px;\n height: 20px;\n display: flex;\n align-items: center;\n justify-content: center;\n border-radius: 4px;\n transition: background 0.12s, color 0.12s;\n flex-shrink: 0;\n}\n.iwb-layer-lock:hover, .iwb-layer-lock.active { background: #45475a; color: #e8a735; }\n\n.iwb-layer-del {\n background: none;\n border: none;\n color: #585b70;\n cursor: pointer;\n font-size: 12px;\n width: 18px;\n height: 18px;\n display: flex;\n align-items: center;\n justify-content: center;\n border-radius: 4px;\n transition: background 0.12s, color 0.12s;\n flex-shrink: 0;\n}\n.iwb-layer-del:hover { background: #cf222e; color: #fff; }\n\n/* SVG 图标尺寸 */\n.iwb-layer-vis svg { display: block; }\n.iwb-layer-icon svg { display: block; }\n.iwb-layer-lock svg { display: block; }\n.iwb-layer-del svg { display: block; }\n\n/* 独立 PS 风格颜色面板 */\n.iwb-editor-color-panel { padding: 12px; border-bottom: 1px solid #313244; background: #202033; }\n.iwb-editor-color-panel-title { color: #cdd6f4; font-size: 12px; font-weight: 600; margin-bottom: 10px; }\n.iwb-editor-color-panel-main { display: flex; align-items: center; gap: 10px; }\n.iwb-editor-color-current { width: 52px; height: 52px; border: 2px solid #cdd6f4; border-radius: 6px; overflow: hidden; display: block; background: #ff4444; }\n.iwb-editor-color-panel-input { width: 100%; height: 100%; padding: 0; border: 0; cursor: pointer; opacity: 0; }\n.iwb-editor-color-panel-values { min-width: 0; flex: 1; }\n.iwb-editor-color-hex { color: #cdd6f4; font: 600 12px monospace; display: block; margin-bottom: 8px; }\n.iwb-editor-color-swatches { display: flex; flex-wrap: wrap; gap: 6px; }\n.iwb-editor-color-panel-swatch { width: 20px; height: 20px; border: 1px solid #585b70; border-radius: 4px; cursor: pointer; }\n.iwb-editor-color-panel-swatch:hover { transform: scale(1.12); border-color: #fff; }\n.iwb-editor-panel-width { display: flex; align-items: center; gap: 8px; margin-top: 12px; color: #a6adc8; font-size: 11px; }\n.iwb-editor-panel-width-range { flex: 1; min-width: 60px; }\n.iwb-editor-panel-width-num { width: 42px; padding: 3px; background: #313244; color: #e8a735; border: 1px solid #45475a; border-radius: 4px; text-align: center; }\n\n/* 顶部独立操作区,避免操作按钮被竖向工具栏裁切 */\n.iwb-editor-actions { display: flex; align-items: center; gap: 5px; margin-left: auto; flex: 0 0 auto; }\n.iwb-editor-actions .iwb-editor-action { position: static !important; }\n.iwb-editor-actions .iwb-editor-action-restore { width: auto; padding: 0 9px; font-size: 12px; }\n\n/* 原图 canvas 只负责绘制像素,透明处透出 stack 的棋盘格。 */\n.iwb-editor-base { background: transparent !important; background-image: none !important; }\n\n/* 透明区域使用 Photoshop 风格的灰色棋盘格,覆盖整个实际图片区域。 */\n.iwb-editor-canvas-stack {\n background-color: #d6d6d6 !important;\n background-image:\n linear-gradient(45deg, #b8b8b8 25%, transparent 25%),\n linear-gradient(-45deg, #b8b8b8 25%, transparent 25%),\n linear-gradient(45deg, transparent 75%, #b8b8b8 75%),\n linear-gradient(-45deg, transparent 75%, #b8b8b8 75%) !important;\n background-size: 20px 20px !important;\n background-position: 0 0, 0 10px, 10px -10px, -10px 0 !important;\n}\n.iwb-editor-base { background: transparent !important; background-image: none !important; }\n\n/* 顶部参数区必须保持可见且可交互,避免被侧栏定位层覆盖。 */\n.iwb-editor-header { position: relative; min-height: 56px; overflow: visible; }\n.iwb-editor-params { position: relative; z-index: 30; overflow: visible; pointer-events: auto; }\n.iwb-editor-params input, .iwb-editor-params button, .iwb-editor-params label { pointer-events: auto; }\n.iwb-editor-brush-size, .iwb-editor-brush-hardness, .iwb-editor-brush-opacity { min-width: 70px; accent-color: #e8a735; }\n.iwb-editor-brush-num, .iwb-editor-eraser-num { pointer-events: auto; }\n\n/* canvas 的透明像素必须透出 stack 棋盘格,不能被黑色工作区遮住。 */\n.iwb-editor-canvas-stack { isolation: isolate; }\n.iwb-editor-layer-canvas, .iwb-editor-text, .iwb-editor-stroke, .iwb-editor-crop-overlay { background: transparent !important; }\n\n/* 透明棋盘格只覆盖原图的显示矩形,外围裁剪扩展区保持纯色。 */\n.iwb-editor-canvas-stack { background: #11111b !important; background-image: none !important; }\n.iwb-editor-transparency-grid { position: absolute; z-index: 0; pointer-events: none; background-color: #d6d6d6; background-image: linear-gradient(45deg, #b8b8b8 25%, transparent 25%), linear-gradient(-45deg, #b8b8b8 25%, transparent 25%), linear-gradient(45deg, transparent 75%, #b8b8b8 75%), linear-gradient(-45deg, transparent 75%, #b8b8b8 75%); background-size: 20px 20px; background-position: 0 0, 0 10px, 10px -10px, -10px 0; }\n.iwb-editor-layer-canvas, .iwb-editor-stroke, .iwb-editor-text { z-index: 1; }\n.iwb-editor-crop-overlay { z-index: 10; }\n\n/* 画布扩展区不得盖过编辑器外围,图片区域由透明层单独标识。 */\n.iwb-editor-canvas-stack { overflow: visible; max-width: 100%; max-height: 100%; background: #11111b !important; background-image: none !important; }\n.iwb-editor-transparency-grid { z-index: 0; overflow: hidden; }\n.iwb-editor-layer-canvas { z-index: 1; }\n.iwb-editor-stroke { z-index: 4; }\n.iwb-editor-text { z-index: 5; }\n.iwb-editor-crop-overlay { z-index: 10; }\n\n/* 导出操作与缩放同处顶栏,缩放独立靠右。 */\n.iwb-editor-export-actions { display: flex; align-items: center; gap: 6px; margin-left: 10px; flex: 0 0 auto; }\n.iwb-editor-export-actions .iwb-editor-btn { padding: 6px 10px; font-size: 11px; }\n.iwb-editor-footer { display: none !important; }\n\n.iwb-editor-export-actions { display: flex; align-items: center; gap: 6px; margin-left: 10px; flex: 0 0 auto; }\n.iwb-editor-export-actions .iwb-editor-btn { padding: 6px 10px; font-size: 11px; }\n.iwb-editor-footer { display: none !important; }\n\n/* 顶部七个操作按钮统一文本按钮样式,自适应中文宽度。 */\n.iwb-editor-actions { gap: 6px; }\n.iwb-editor-actions .iwb-editor-action { width: auto; min-width: 72px; height: 32px; padding: 0 12px; gap: 5px; font-size: 12px; font-weight: 500; white-space: nowrap; }\n.iwb-editor-actions .iwb-editor-action svg { width: 14px; height: 14px; flex: 0 0 auto; }\n.iwb-editor-export-actions .iwb-editor-btn { min-width: 72px; white-space: nowrap; }\n\n/* 顶部操作按钮统一为纯文本,图标隐藏并保持一致宽度。 */\n.iwb-editor-actions .iwb-editor-action svg { display: none !important; }\n.iwb-editor-actions .iwb-editor-action { min-width: 76px; width: 76px; justify-content: center; background: #3b3d52; color: #cdd6f4; }\n.iwb-editor-actions .iwb-editor-action:hover { background: #50536b; }\n.iwb-editor-actions .iwb-editor-action-restore { background: #3b3d52; color: #cdd6f4; }\n.iwb-editor-actions .iwb-editor-action-restore:hover { background: #50536b !important; }\n\n.iwb-editor-actions .iwb-editor-action svg { display: none !important; }\n.iwb-editor-actions .iwb-editor-action { min-width: 76px; width: 76px; justify-content: center; background: #3b3d52; color: #cdd6f4; }\n.iwb-editor-actions .iwb-editor-action:hover, .iwb-editor-actions .iwb-editor-action-restore:hover { background: #50536b !important; }\n\n.iwb-editor-actions .iwb-editor-action { width: auto; min-width: 76px; padding: 0 12px; gap: 5px; }\n.iwb-editor-actions .iwb-editor-action span { display: inline-block; }\n\n.iwb-editor-actions { margin-left: 12px; }\n.iwb-editor-actions .iwb-editor-btn { width: auto; min-width: 76px; height: 32px; padding: 0 12px; font-size: 12px; white-space: nowrap; }\n.iwb-editor-actions .iwb-editor-action { width: auto; min-width: 76px; }\n\n.iwb-editor-actions .iwb-editor-action { min-width: 52px; width: auto; padding: 0 10px; font-size: 12px; }\n.iwb-editor-brush-presets { display: flex; align-items: center; gap: 7px; margin-left: 4px; }\n.iwb-editor-brush-preset { display: inline-flex; align-items: center; gap: 3px; padding: 2px 3px; border: 0; background: transparent; color: #a6adc8; cursor: pointer; font-size: 11px; }\n.iwb-editor-brush-preset i { display: block; width: 12px; height: 12px; border-radius: 50%; background: #e8a735; border: 1px solid #f6d38a; }\n.iwb-editor-brush-preset:nth-child(2) i { width: 16px; height: 16px; }\n.iwb-editor-brush-preset:nth-child(3) i { width: 20px; height: 20px; }\n.iwb-editor-brush-preset:nth-child(4) i { width: 24px; height: 24px; }\n.iwb-editor-brush-preset:hover, .iwb-editor-brush-preset.active { color: #fff; }\n\n/* 紧凑顶栏:操作按钮与描边快捷点仅保留必要视觉信息。 */\n.iwb-editor-actions .iwb-editor-action { width: 28px; min-width: 28px; height: 28px; padding: 0; }\n.iwb-editor-actions .iwb-editor-action svg { display: block !important; width: 14px; height: 14px; }\n.iwb-editor-brush-presets { gap: 5px; margin-left: 2px; }\n.iwb-editor-brush-preset { width: 24px; height: 24px; padding: 0; justify-content: center; }\n.iwb-editor-brush-preset i { width: 5px; height: 5px; }\n.iwb-editor-brush-preset:nth-child(2) i { width: 8px; height: 8px; }\n.iwb-editor-brush-preset:nth-child(3) i { width: 12px; height: 12px; }\n.iwb-editor-brush-preset:nth-child(4) i { width: 16px; height: 16px; }\n\n/* 图层栏内嵌调色板:颜色直接点击应用,不弹出系统取色器。 */\n.iwb-editor-color-panel { padding: 10px; }\n.iwb-editor-color-current { width: 42px; height: 42px; flex: 0 0 42px; cursor: default; }\n.iwb-editor-color-swatches { display: grid; grid-template-columns: repeat(7, 20px); gap: 5px; }\n.iwb-editor-color-panel-swatch { width: 20px; height: 20px; border-radius: 50%; }\n\n.iwb-editor-color-panel { padding: 10px; }\n.iwb-editor-color-current { width: 42px; height: 42px; flex: 0 0 42px; cursor: default; }\n.iwb-editor-color-swatches { display: grid; grid-template-columns: repeat(7, 20px); gap: 5px; }\n.iwb-editor-color-panel-swatch { width: 20px; height: 20px; border-radius: 50%; }\n\n.iwb-editor-color-panel { padding: 10px; }\n.iwb-editor-palette-current { display: flex; align-items: center; gap: 8px; margin-bottom: 9px; }\n.iwb-editor-palette-current .iwb-editor-color-current { width: 26px; height: 26px; flex: 0 0 26px; border-radius: 4px; }\n.iwb-editor-color-panel .iwb-editor-color-hex { margin: 0; }\n.iwb-editor-color-panel .iwb-editor-color-swatches { display: grid; grid-template-columns: repeat(6, 20px); gap: 7px; }\n.iwb-editor-color-panel .iwb-editor-color-panel-swatch { width: 20px; height: 20px; border-radius: 50%; padding: 0; }\n.iwb-editor-color-panel .iwb-editor-color-panel-swatch.active { outline: 2px solid #fff; outline-offset: 2px; }\n\n.iwb-editor-color-panel { padding: 10px; }\n.iwb-editor-palette-current { display: flex; align-items: center; gap: 8px; margin-bottom: 9px; }\n.iwb-editor-palette-current .iwb-editor-color-current { width: 26px; height: 26px; flex: 0 0 26px; border-radius: 4px; }\n.iwb-editor-color-panel .iwb-editor-color-hex { margin: 0; }\n.iwb-editor-color-panel .iwb-editor-color-swatches { display: grid; grid-template-columns: repeat(6, 20px); gap: 7px; }\n.iwb-editor-color-panel .iwb-editor-color-panel-swatch { width: 20px; height: 20px; border-radius: 50%; padding: 0; }\n.iwb-editor-color-panel .iwb-editor-color-panel-swatch.active { outline: 2px solid #fff; outline-offset: 2px; }\n\n.iwb-editor-inline-picker { display: flex; align-items: center; gap: 8px; margin-bottom: 9px; }\n.iwb-editor-inline-picker .iwb-editor-color-panel-input { width: 42px; height: 28px; padding: 0; opacity: 1; cursor: pointer; border: 1px solid #585b70; border-radius: 4px; }\n.iwb-editor-color-panel .iwb-editor-color-swatches { display: grid; grid-template-columns: repeat(6, 20px); gap: 7px; }\n.iwb-editor-color-panel .iwb-editor-color-panel-swatch { width: 20px; height: 20px; border-radius: 50%; padding: 0; }\n\n.iwb-editor-inline-picker { display: flex; align-items: center; gap: 8px; margin-bottom: 9px; }\n.iwb-editor-inline-picker .iwb-editor-color-panel-input { width: 42px; height: 28px; padding: 0; opacity: 1; cursor: pointer; border: 1px solid #585b70; border-radius: 4px; }\n.iwb-editor-color-panel .iwb-editor-color-swatches { display: grid; grid-template-columns: repeat(6, 20px); gap: 7px; }\n.iwb-editor-color-panel .iwb-editor-color-panel-swatch { width: 20px; height: 20px; border-radius: 50%; padding: 0; }\n\n.iwb-editor-inline-picker { display: flex; align-items: center; gap: 8px; margin-bottom: 9px; }\n.iwb-editor-inline-picker .iwb-editor-color-panel-input { width: 42px; height: 28px; padding: 0; opacity: 1; cursor: pointer; border: 1px solid #585b70; border-radius: 4px; }\n.iwb-editor-color-panel .iwb-editor-color-swatches { display: grid; grid-template-columns: repeat(6, 20px); gap: 7px; }\n.iwb-editor-color-panel .iwb-editor-color-panel-swatch { width: 20px; height: 20px; border-radius: 50%; padding: 0; }\n\n.iwb-editor-color-panel { padding: 9px; }\n.iwb-editor-inline-picker { display: flex; align-items: center; gap: 8px; margin-bottom: 8px; }\n.iwb-editor-inline-picker .iwb-editor-color-panel-input { display: block; width: 44px; height: 30px; padding: 0; opacity: 1; cursor: pointer; border: 1px solid #585b70; border-radius: 4px; }\n.iwb-editor-color-panel .iwb-editor-color-swatches { display: grid; grid-template-columns: repeat(6, 20px); gap: 7px; }\n.iwb-editor-color-panel .iwb-editor-color-panel-swatch { width: 20px; height: 20px; border-radius: 50%; padding: 0; }\n.iwb-editor-color-panel .iwb-editor-color-panel-swatch.active { outline: 2px solid #fff; outline-offset: 2px; }\n\n.iwb-editor-color-picker2 { display: flex; gap: 8px; height: 118px; }\n.iwb-color-sv { position: relative; flex: 1; background: linear-gradient(to top,#000,transparent),linear-gradient(to right,#fff,rgba(255,255,255,0)); background-color: #f44; border-radius: 4px; }\n.iwb-color-hue { width: 18px; border-radius: 4px; background: linear-gradient(to bottom,#f00,#ff0,#0f0,#0ff,#00f,#f0f,#f00); }\n.iwb-editor-color-fields { display: flex; gap: 6px; margin: 8px 0; }\n.iwb-editor-color-hex-input { width: 72px; background:#313244; color:#cdd6f4; border:1px solid #585b70; padding:4px; }\n.iwb-editor-color-panel-input { width: 32px; height: 26px; opacity: 1; padding: 0; }\n\n.iwb-color-sv span, .iwb-color-hue span { position: absolute; width: 10px; height: 10px; border: 2px solid #fff; border-radius: 50%; box-shadow: 0 0 0 1px #222; transform: translate(-50%, -50%); pointer-events: none; }\n.iwb-color-sv span { left: 100%; top: 0; }\n.iwb-color-hue span { left: 50%; top: 0; }\n\n.iwb-compress-btn { color: #16a34a !important; font-size: 11px; font-weight: 700; }\n\n/* 新版浮动气泡栏内的工具按钮 */\n.iwb-node-floatbar .iwb-compress-btn { font-size: 11px; font-weight: 700; }\n.iwb-node-floatbar .iwb-cutout-btn.processing,\n.iwb-node-floatbar .iwb-whitebg-btn.processing,\n.iwb-node-floatbar .iwb-compress-btn.processing { animation: iwb-cutout-pulse 1s infinite; pointer-events: none; }\n\n\n/* 调色板:吸色按钮(替代原来的弹出式取色器) */\n.iwb-editor-color-eye { width: 26px; height: 26px; border: 1px solid #585b70; border-radius: 4px; background: #313244; color: #cdd6f4; cursor: pointer; display: inline-flex; align-items: center; justify-content: center; padding: 0; }\n.iwb-editor-color-eye:hover { border-color: #e8a735; color: #e8a735; }\n\n/* 矢量对象独立画布:与位图图层统一参与 z 排序 */\n.iwb-editor-vec-canvas { position: absolute; top: 0; left: 0; z-index: 1; background: transparent !important; }\n\n/* 空白画布创建菜单 */\n.iwb-blank-menu { position: fixed; width: 242px; background: #fff; border: 1px solid #d0d7de; border-radius: 12px; box-shadow: 0 12px 32px rgba(15,23,42,.2); padding: 10px; z-index: 2147483000; font-size: 12px; color: #1f2328; }\n.iwb-blank-menu .iwb-blank-title { font-weight: 700; font-size: 12px; margin-bottom: 8px; }\n.iwb-blank-menu .iwb-blank-bg, .iwb-blank-menu .iwb-blank-res { display: flex; align-items: center; gap: 5px; margin-bottom: 7px; }\n.iwb-blank-menu .iwb-blank-bg span, .iwb-blank-menu .iwb-blank-res span { color: #656d76; min-width: 26px; }\n.iwb-blank-menu button { border: 1px solid #d0d7de; background: #f6f8fa; color: #1f2328; border-radius: 6px; padding: 3px 8px; cursor: pointer; font-size: 11px; }\n.iwb-blank-menu button:hover { background: #eff2f4; }\n.iwb-blank-menu button.on { background: #0ea5e9; border-color: #0ea5e9; color: #fff; }\n.iwb-blank-menu .iwb-blank-grid { display: grid; grid-template-columns: 1fr 1fr; gap: 6px; margin-top: 4px; }\n.iwb-blank-menu .iwb-blank-grid button { display: flex; flex-direction: column; gap: 1px; align-items: center; padding: 5px 4px; }\n.iwb-blank-menu .iwb-blank-grid b { font-weight: 600; }\n.iwb-blank-menu .iwb-blank-grid i { font-style: normal; color: #656d76; font-size: 10px; }\n\n/* 空参考图节点:常驻“空白画布”按钮(位于节点顶部中央) */\n.iwb-blank-inline-btn { position: absolute; top: 10px; left: 50%; transform: translateX(-50%); z-index: 6; display: inline-flex; align-items: center; gap: 5px; background: #fff; border: 1px solid #d0d7de; border-radius: 14px; padding: 4px 11px; color: #0ea5e9; font-size: 11px; font-weight: 600; cursor: pointer; box-shadow: 0 2px 8px rgba(0,0,0,0.08); }\n.iwb-blank-inline-btn:hover { background: #f0f9ff; border-color: #0ea5e9; }\n.iwb-blank-inline-btn svg { width: 13px; height: 13px; }\n\n/* ============ UI 布局重构(参照 excalidraw) ============ */\n/* 顶部:功能按钮在左,工具栏横排整行、按快捷键排序并带数字角标 */\n.iwb-editor-header { flex-wrap: wrap; }\n.iwb-editor-header > .iwb-editor-title { order: 1; }\n.iwb-editor-header > .iwb-editor-actions { order: 2; }\n.iwb-editor-header > .iwb-editor-tools {\n position: static;\n order: 3;\n flex: 1 1 100%;\n width: auto;\n left: auto;\n top: auto;\n margin-top: 8px;\n flex-direction: row;\n justify-content: center;\n padding: 6px 10px;\n border-radius: 10px;\n}\n.iwb-editor-tool { position: relative; }\n.iwb-tool-key {\n position: absolute;\n right: -3px;\n bottom: -3px;\n font-size: 8px;\n line-height: 1;\n background: #45475a;\n color: #cdd6f4;\n padding: 1px 3px;\n border-radius: 3px;\n pointer-events: none;\n font-style: normal;\n font-weight: 600;\n}\n.iwb-editor-tool.active .iwb-tool-key { background: #1e1e2e; color: #e8a735; }\n.iwb-editor-header > .iwb-editor-tools .iwb-editor-divider { width: 1px; height: 22px; margin: 0 6px; }\n\n/* 左侧:工具参数设定栏(缩放/实心/图层/描边/硬度/透明度) */\n.iwb-editor-params {\n width: 216px;\n min-width: 216px;\n flex: 0 0 216px;\n flex-direction: column;\n align-items: stretch;\n gap: 12px;\n margin-left: 0;\n padding: 14px 12px;\n background: #181825;\n border-right: 1px solid #313244;\n overflow-y: auto;\n}\n.iwb-editor-params .iwb-editor-zoom { margin-left: 0; order: 0; }\n.iwb-editor-params .iwb-editor-zoom .iwb-editor-zoom-val { min-width: 52px; text-align: center; }\n.iwb-editor-params .iwb-editor-layer-group { flex-wrap: wrap; justify-content: flex-start; }\n.iwb-editor-params .iwb-editor-brush-label { width: 100%; }\n.iwb-editor-params .iwb-editor-brush-presets { justify-content: flex-start; }\n.iwb-editor-params .iwb-editor-fill-btn { align-self: stretch; }\n.iwb-editor-main { display: flex; flex-direction: row; }\n\n/* ======== 布局重构 v2(按用户 6 点) ======== */\n.iwb-editor-main { display: flex; flex-direction: row; align-items: stretch; }\n\n/* 顶部一行:标题 + 工具栏(含数字角标) + 撤销重做清空还原 */\n.iwb-editor-header { flex-wrap: nowrap; align-items: center; }\n.iwb-editor-header > .iwb-editor-title { order: 0; }\n.iwb-editor-header > .iwb-editor-tools {\n position: static; order: 1; flex: 1 1 auto; flex-basis: auto;\n margin-top: 0; width: auto; left: auto; top: auto;\n flex-direction: row; justify-content: center;\n padding: 0; background: transparent; border: 0; border-radius: 0;\n}\n.iwb-editor-header > .iwb-editor-divider { order: 2; }\n.iwb-editor-header > .iwb-editor-history { order: 3; display: flex; align-items: center; gap: 4px; }\n\n/* 左栏:调色板在上,参数竖排,导出按钮底部 */\n.iwb-editor-left {\n width: 240px; min-width: 240px; flex: 0 0 240px;\n display: flex; flex-direction: column; gap: 14px;\n padding: 12px; background: #181825; border-right: 1px solid #313244; overflow-y: auto;\n}\n.iwb-editor-left > .iwb-editor-color-panel { padding: 0; background: transparent; border-bottom: 0; }\n.iwb-editor-left > .iwb-editor-params {\n width: auto; min-width: 0; flex: 1 1 auto;\n flex-direction: column; align-items: stretch; gap: 12px; margin-left: 0; padding: 0;\n}\n.iwb-editor-left > .iwb-editor-export-actions {\n display: flex; flex-direction: column; gap: 8px;\n margin-top: auto; padding-top: 12px; border-top: 1px solid #313244;\n}\n.iwb-editor-left > .iwb-editor-export-actions .iwb-editor-btn { width: 100%; }\n\n/* 参数竖排:一行一个设置 */\n.iwb-editor-params .iwb-editor-brush-group { display: flex; flex-direction: column; gap: 10px; }\n.iwb-editor-params .iwb-editor-zoom .iwb-editor-zoom-btn,\n.iwb-editor-params .iwb-editor-zoom .iwb-editor-zoom-val { flex: 1 1 auto; }\n.iwb-editor-params .iwb-editor-layer-group { flex-wrap: wrap; }\n\n/* 颜色值后面的 实心/边线 切换 */\n.iwb-editor-fill-pair { display: inline-flex; margin-left: 6px; }\n.iwb-editor-fill-pair .iwb-editor-fill-btn { align-self: center; }\n\n/* ======== 布局优化 v3 ======== */\n/* 左栏可交互(避免被画布/层级遮挡导致“调节不起作用”) */\n.iwb-editor-left { position: relative; z-index: 40; pointer-events: auto; }\n.iwb-editor-left input, .iwb-editor-left select, .iwb-editor-left button, .iwb-editor-left label { pointer-events: auto; }\n\n/* 顶部工具栏内的 面/边(实心) 切换按钮 */\n.iwb-editor-tools .iwb-editor-fill-btn {\n width: 42px; height: 32px; padding: 0; border: 0; border-radius: 8px;\n background: transparent; color: #cdd6f4; cursor: pointer; font-size: 11px; font-weight: 600;\n}\n.iwb-editor-tools .iwb-editor-fill-btn:hover { background: #45475a; }\n.iwb-editor-tools .iwb-editor-fill-btn.active { background: #e8a735; color: #1e1e2e; }\n\n/* 右侧图层面板内的图层顺序按钮 */\n.iwb-editor-layer-panel .iwb-editor-layer-group {\n display: flex; align-items: center; gap: 6px;\n padding: 10px 12px; border-bottom: 1px solid #313244;\n}\n.iwb-editor-layer-panel .iwb-editor-layer-group .iwb-editor-constraint-label { color: #a6adc8; font-size: 12px; margin-right: 2px; }\n\n/* 缩放(画面调整)移到左栏下方 */\n.iwb-editor-params .iwb-editor-zoom {\n order: 99; margin-top: 10px; padding-top: 10px; border-top: 1px solid #313244;\n}\n.iwb-editor-params .iwb-editor-zoom .iwb-editor-zoom-btn { flex: 0 0 auto; }\n.iwb-editor-params .iwb-editor-zoom .iwb-editor-zoom-val { flex: 0 0 auto; }\n\n/* ======== 布局优化 v4 ======== */\n/* 交换左右栏:图层在左,调色板/参数在右 */\n.iwb-editor-main { flex-direction: row; }\n.iwb-editor-main > .iwb-editor-layer-panel { order: 1; border-left: 0; border-right: 1px solid #313244; }\n.iwb-editor-main > .iwb-editor-canvas-wrap { order: 2; }\n.iwb-editor-left { order: 3; border-right: 0; border-left: 1px solid #313244; }\n\n/* 硬度/透明度 数值与滑块对齐 */\n.iwb-editor-params .iwb-editor-brush-label .iwb-editor-brush-hardness-val,\n.iwb-editor-params .iwb-editor-brush-label .iwb-editor-brush-opacity-val {\n min-width: 40px; text-align: right; color: #cdd6f4; font-size: 12px;\n}\n.iwb-editor-params .iwb-editor-brush-label input[type="range"] { flex: 1 1 auto; }\n\n/* 缩放块放在参数区最底部 */\n.iwb-editor-params .iwb-editor-zoom, .iwb-editor-left .iwb-editor-zoom {\n display: flex; align-items: center; justify-content: center; gap: 8px;\n width: 100%; padding: 8px 4px; border-top: 1px solid #313244; margin-top: 12px;\n}\n.iwb-editor-left .iwb-editor-zoom .iwb-editor-zoom-btn {\n flex: 0 0 auto; min-width: 28px; height: 26px; background: #313244; color: #cdd6f4; border: 0; border-radius: 6px; cursor: pointer; font-size: 14px;\n}\n.iwb-editor-left .iwb-editor-zoom .iwb-editor-zoom-btn:hover { background: #45475a; }\n.iwb-editor-left .iwb-editor-zoom .iwb-editor-zoom-val { min-width: 52px; text-align: center; color: #cdd6f4; font: 600 12px sans-serif; }\n\n/* 调色板与下方参数调节之间的横线分割 */\n.iwb-editor-params { border-top: 1px solid #313244; padding-top: 12px; }\n\n/* 色相条指示器需定位父级相对 */\n.iwb-color-hue { position: relative; }\n\n/* 顶部实心按钮与工具匹配:默认背景 */\n.iwb-editor-tools .iwb-editor-fill-btn { background: #313244; color: #cdd6f4; }\n\n/* 裁剪工具条:三行展示(比例 / 尺寸 / 确认取消),避免被挤压 */\n.iwb-editor-crop-bar {\n display: flex;\n flex-direction: column;\n gap: 8px;\n align-items: center;\n padding: 10px 14px;\n}\n.iwb-editor-crop-row { display: flex; align-items: center; justify-content: center; flex-wrap: wrap; width: 100%; gap: 6px; }\n.iwb-editor-crop-row .iwb-editor-constraint-group { display: flex; align-items: center; flex-wrap: wrap; gap: 5px; }\n.iwb-editor-crop-actions { gap: 10px; }\n.iwb-editor-crop-actions .iwb-editor-crop-info { min-width: 88px; text-align: center; }\n.iwb-editor-constraint-sep { display: none; }\n\n/* ======== 修复:左列(图层)占满高度,三列稳定布局 ======== */\n.iwb-editor-main { display: flex; flex-direction: row; align-items: stretch; }\n.iwb-editor-main > .iwb-editor-layer-panel { flex: 0 0 290px; min-width: 290px; width: 290px; }\n.iwb-editor-main > .iwb-editor-canvas-wrap { flex: 1 1 auto; min-width: 0; }\n.iwb-editor-left { flex: 0 0 240px; min-width: 240px; width: 240px; }\n.iwb-editor-layer-panel .iwb-editor-layer-list { flex: 1 1 auto; min-height: 0; overflow-y: auto; }\n\n/* ======== 顶部布局 v5:左侧重置类 / 中间工具 / 右侧保存类 ======== */\n.iwb-editor-header > .iwb-editor-title { order: 0; }\n.iwb-editor-header > .iwb-editor-history { order: 1; display: flex; align-items: center; gap: 4px; }\n.iwb-editor-header > .iwb-editor-tools { order: 2; flex: 1 1 auto; justify-content: center; }\n.iwb-editor-header > .iwb-editor-export-actions { order: 3; display: flex; align-items: center; gap: 6px; margin-left: 4px; }\n\n/* 重置类(撤销/重做/清空/复原)统一小圆角按钮 */\n.iwb-editor-header .iwb-editor-history .iwb-editor-action {\n width: 30px; height: 30px; padding: 0; border: 0; border-radius: 8px;\n background: #313244; color: #cdd6f4; display: inline-flex; align-items: center; justify-content: center; cursor: pointer;\n}\n.iwb-editor-header .iwb-editor-history .iwb-editor-action:hover { background: #45475a; }\n.iwb-editor-header .iwb-editor-history .iwb-editor-action-restore { background: #313244; color: #cdd6f4; }\n\n/* 保存类(新建/覆盖/退出)统一样式 */\n.iwb-editor-header .iwb-editor-export-actions .iwb-editor-btn {\n height: 30px; padding: 0 14px; border: 0; border-radius: 8px; font-size: 12px; font-weight: 600;\n background: #313244; color: #cdd6f4; cursor: pointer;\n}\n.iwb-editor-header .iwb-editor-export-actions .iwb-editor-btn:hover { background: #45475a; }\n\n/* 调色板与参数之间的分割线及间距 */\n.iwb-editor-left > .iwb-editor-params { border-top: 1px solid #313244; margin-top: 16px; padding-top: 16px; }\n\n/* 笔刷快捷值 7 档圆点 */\n.iwb-editor-brush-presets { display: flex; align-items: center; gap: 8px; }\n.iwb-editor-brush-preset i { width: 6px; height: 6px; }\n.iwb-editor-brush-preset:nth-child(2) i { width: 8px; height: 8px; }\n.iwb-editor-brush-preset:nth-child(3) i { width: 10px; height: 10px; }\n.iwb-editor-brush-preset:nth-child(4) i { width: 13px; height: 13px; }\n.iwb-editor-brush-preset:nth-child(5) i { width: 16px; height: 16px; }\n.iwb-editor-brush-preset:nth-child(6) i { width: 20px; height: 20px; }\n.iwb-editor-brush-preset:nth-child(7) i { width: 24px; height: 24px; }\n\n/* 缩放:缩小比例、圆角 */\n.iwb-editor-left .iwb-editor-zoom { gap: 6px; padding: 6px 4px; margin-top: 10px; }\n.iwb-editor-left .iwb-editor-zoom .iwb-editor-zoom-btn { min-width: 26px; height: 24px; border-radius: 8px; font-size: 13px; }\n.iwb-editor-left .iwb-editor-zoom .iwb-editor-zoom-val { min-width: 44px; font-size: 11px; }\n.iwb-editor-left .iwb-editor-zoom .iwb-editor-zoom-fit { font-size: 11px; padding: 0 8px; }\n\n/* 笔刷快捷值:压缩横向间距,避免右栏出现横向滚动条 */\n.iwb-editor-left { overflow-x: hidden; }\n.iwb-editor-params { overflow-x: hidden; }\n.iwb-editor-brush-presets { gap: 3px; flex-wrap: wrap; max-width: 100%; justify-content: flex-start; }\n.iwb-editor-brush-preset { padding: 0 1px; min-width: 0; flex: 0 0 auto; }\n.iwb-editor-brush-preset i { width: 5px; height: 5px; }\n.iwb-editor-brush-preset:nth-child(2) i { width: 7px; height: 7px; }\n.iwb-editor-brush-preset:nth-child(3) i { width: 9px; height: 9px; }\n.iwb-editor-brush-preset:nth-child(4) i { width: 11px; height: 11px; }\n.iwb-editor-brush-preset:nth-child(5) i { width: 14px; height: 14px; }\n.iwb-editor-brush-preset:nth-child(6) i { width: 17px; height: 17px; }\n.iwb-editor-brush-preset:nth-child(7) i { width: 20px; height: 20px; }\n\n/* 去掉参数模块右侧的边线(隐藏纵向滚动条与右边框) */\n.iwb-editor-left { border-right: 0 !important; scrollbar-width: none; -ms-overflow-style: none; }\n.iwb-editor-left::-webkit-scrollbar { width: 0; height: 0; display: none; }\n.iwb-editor-left > .iwb-editor-params { border-right: 0; }\n.iwb-editor-brush-presets::-webkit-scrollbar { width: 0; height: 0; display: none; }\n\n/* 独立悬浮工具条(扩展自建,不插入应用 React DOM) */\n.iwb-cutout-toolbar {\n position: fixed; z-index: 2147483000; display: none; align-items: center; gap: 3px;\n padding: 4px 6px; border-radius: 14px; background: #fff;\n border: 1px solid #d0d7de; box-shadow: 0 8px 28px rgba(15, 23, 42, 0.14);\n pointer-events: auto;\n}\n.iwb-cutout-toolbar button {\n width: 30px; height: 28px; padding: 0; border: 0; border-radius: 8px;\n background: transparent; cursor: pointer; display: inline-flex; align-items: center; justify-content: center;\n}\n.iwb-cutout-toolbar button:hover { background: #eef2f7; }\n.iwb-cutout-toolbar button i { font-style: normal; font-size: 11px; font-weight: 700; }\n.iwb-cutout-toolbar button svg { display: block; }\n\n/* 顶部左右两组工具交换:左=新建/覆盖/退出,右=撤销/重做/清空/复原 */\n.iwb-editor-header > .iwb-editor-title { order: 0; }\n/* 输出设定 + 下载/新建/覆盖/退出 收在顶栏最右侧(用户裁定 2026-11-04):\n order 排最后 + margin-left:auto 兜底,中间工具区 flex:1 会把它顶到右端 */\n.iwb-editor-header > .iwb-editor-export-actions { order: 9; margin-left: auto; margin-right: 0; flex: 0 0 auto; }\n.iwb-editor-header > .iwb-editor-tools { order: 2; flex: 1 1 auto; justify-content: center; }\n.iwb-editor-header > .iwb-editor-history { order: 3; margin-left: 0; }\n\n/* 图层面板:放大锁定 / 删除按钮的点击区域与图标 */\n.iwb-editor-layer-panel .iwb-layer-lock,\n.iwb-editor-layer-panel .iwb-layer-del {\n width: 24px; height: 24px; padding: 0; display: inline-flex; align-items: center; justify-content: center;\n}\n.iwb-editor-layer-panel .iwb-layer-lock svg,\n.iwb-editor-layer-panel .iwb-layer-del svg { width: 16px; height: 16px; }\n\n\n/* 图层按钮图标统一 14px */\n.iwb-editor-layer-panel .iwb-layer-vis svg,\n.iwb-editor-layer-panel .iwb-layer-lock svg,\n.iwb-editor-layer-panel .iwb-layer-del svg { width: 14px; height: 14px; }\n.iwb-editor-layer-panel .iwb-layer-vis,\n.iwb-editor-layer-panel .iwb-layer-lock,\n.iwb-editor-layer-panel .iwb-layer-del { width: 22px; height: 22px; padding: 0; display: inline-flex; align-items: center; justify-content: center; }\n\n/* ================================================================\n v1.1 便利版 UI(单张处理)\n 只追加、不重写历史样式:旧规则里的魔数定位在这里统一覆盖。\n 分区:顶栏 / 就地选项栏 / 竖工具栏 / 画布浮层 / 状态栏 / toast\n ================================================================ */\n\n/* ---- 顶栏:精简、一步可达 ---- */\n.iwb-editor-header { min-height: 44px; padding: 6px 12px; gap: 8px; }\n.iwb-editor-title em.iwb-editor-doc-size { font-style: normal; font-weight: 400; font-size: 11px; color: #7f849c; margin-left: 6px; }\n.iwb-editor-optionbar {\n display: flex; align-items: center; gap: 10px;\n height: 36px; min-height: 36px; padding: 0 12px;\n background: #202033; border-bottom: 1px solid #313244;\n color: #a6adc8; font-size: 12px;\n}\n.iwb-editor-optionbar-label { color: #7f849c; font-weight: 600; white-space: nowrap; }\n.iwb-editor-optionbar-body { display: flex; align-items: center; gap: 8px; flex: 1 1 auto; min-width: 0; }\n/* 右端通用快捷键提示。原来只有 @media 里的 display:none,没有任何基础样式,\n 于是它作为裸 span 参与 flex 收缩,被挤成两行还贴到右边缘外。 */\n.iwb-editor-optionbar-tip {\n flex: 0 0 auto; white-space: nowrap;\n color: #6c7086; font-size: 11px; padding-left: 4px;\n}\n.iwb-opt-label { color: #a6adc8; white-space: nowrap; }\n.iwb-opt-btn {\n background: #313244; color: #cdd6f4; border: 1px solid transparent; border-radius: 5px;\n padding: 3px 9px; font-size: 12px; cursor: pointer;\n}\n.iwb-opt-btn:hover { background: #45475a; }\n.iwb-opt-btn.active { background: #4488ff; color: #fff; }\n.iwb-opt-num {\n width: 46px; padding: 2px 4px; background: #313244; color: #e8a735;\n border: 1px solid #45475a; border-radius: 5px; text-align: center; font-size: 12px;\n}\n.iwb-opt-current { color: #e8a735; font-weight: 600; white-space: nowrap; }\n/* hint 是「说明」不是「控件」:不许被压缩。\n 早先带 text-overflow:ellipsis,在 36px 高的选项栏里会被压成「双击改…」这种半截文案,\n 比不显示更误导人;现在由父级 overflow-x 决定是完整显示还是整体滚出视野。 */\n.iwb-opt-hint { color: #7f849c; font-size: 11px; margin-left: auto; white-space: nowrap; flex: 0 0 auto; }\n\n.iwb-editor-more-wrap, .iwb-editor-export-settings-wrap { position: relative; flex: 0 0 auto; z-index: 45; }\n.iwb-editor-more-btn, .iwb-editor-panel-toggle, .iwb-editor-export-settings-btn {\n background: #313244; color: #cdd6f4; border: 1px solid #45475a; border-radius: 6px;\n padding: 5px 10px; font-size: 12px; cursor: pointer; white-space: nowrap;\n}\n.iwb-editor-more-btn:hover, .iwb-editor-panel-toggle:hover, .iwb-editor-export-settings-btn:hover { background: #45475a; }\n.iwb-editor-panel-toggle { padding: 5px 8px; }\n.iwb-editor-export-summary { color: #e8a735; margin: 0 2px; }\n\n.iwb-editor-more-menu, .iwb-editor-export-settings {\n display: none; position: absolute; top: 34px; z-index: 60;\n background: #252537; border: 1px solid #45475a; border-radius: 8px;\n padding: 6px; box-shadow: 0 10px 30px rgba(0,0,0,0.45);\n}\n.iwb-editor-more-menu { left: 0; width: 206px; flex-direction: column; gap: 2px; }\n.iwb-editor-more-menu.open, .iwb-editor-export-settings.open { display: flex; flex-direction: column; gap: 4px; }\n.iwb-editor-export-settings { right: 0; width: 268px; }\n.iwb-editor-more-menu button, .iwb-editor-export-row button {\n background: transparent; color: #cdd6f4; border: 0; border-radius: 5px;\n padding: 6px 8px; font-size: 12px; text-align: left; cursor: pointer; white-space: nowrap;\n}\n.iwb-editor-more-menu button:hover, .iwb-editor-export-row button:hover { background: #3b3d52; }\n.iwb-editor-more-menu kbd { float: right; color: #7f849c; font-size: 10px; }\n.iwb-editor-more-sep { height: 1px; background: #45475a; margin: 4px 0; }\n.iwb-editor-export-row { display: flex; align-items: center; gap: 4px; }\n.iwb-editor-export-row > span { width: 34px; flex: 0 0 34px; color: #7f849c; font-size: 11px; }\n.iwb-editor-export-row button { flex: 1 1 auto; text-align: center; background: #313244; }\n.iwb-editor-export-row button.active { background: #4488ff; color: #fff; }\n.iwb-editor-export-note { color: #7f849c; font-size: 11px; border-top: 1px solid #313244; padding-top: 6px; }\n.iwb-editor-btn-download { background: #1a7f37 !important; color: #fff !important; }\n.iwb-editor-btn-download:hover { background: #15803d !important; }\n\n/* ---- v1.2.8:底部浮动工具栏(Figma 风格,横排悬浮在画布底部居中) ----\n 工具栏已从 header 移进 canvas-wrap,只占画布区域宽度,不挤压左右面板;\n bottom 距容器 14px,配合 computeFit() 预留的底部空间,图片不会被压住。 */\n.iwb-editor-canvas-wrap > .iwb-editor-tools {\n position: absolute; left: 50%; bottom: 14px; transform: translateX(-50%);\n display: flex; flex-direction: row; align-items: center; gap: 2px;\n padding: 5px 8px; border-radius: 14px;\n background: rgba(24, 24, 37, 0.94);\n border: 1px solid #313244;\n box-shadow: 0 12px 32px rgba(0, 0, 0, 0.5);\n -webkit-backdrop-filter: blur(10px); backdrop-filter: blur(10px);\n z-index: 40;\n max-width: calc(100% - 28px);\n overflow-x: auto; overflow-y: hidden; scrollbar-width: none;\n}\n.iwb-editor-canvas-wrap > .iwb-editor-tools::-webkit-scrollbar { display: none; }\n.iwb-editor-canvas-wrap > .iwb-editor-tools .iwb-editor-tool,\n.iwb-editor-canvas-wrap > .iwb-editor-tools .iwb-editor-action {\n width: 32px !important; height: 32px !important; min-width: 32px; flex: 0 0 auto; border-radius: 9px;\n}\n.iwb-editor-canvas-wrap > .iwb-editor-tools .iwb-editor-divider {\n width: 1px; height: 20px; margin: 0 5px; flex: 0 0 auto; background: #45475a;\n}\n.iwb-editor-main { padding-left: 0; }\n.iwb-editor-main > .iwb-editor-layer-panel { flex: 0 0 260px !important; min-width: 260px !important; width: 260px !important; }\n.iwb-editor-left { flex: 0 0 220px !important; min-width: 220px !important; width: 220px !important; }\n.iwb-editor-overlay.panels-collapsed .iwb-editor-layer-panel,\n.iwb-editor-overlay.panels-collapsed .iwb-editor-left { display: none !important; }\n.iwb-editor-zoom-hint { display: none !important; }\n\n/* ---- 交互层:蚂蚁线 / 笔刷环各自独立,互不擦除 ---- */\n.iwb-editor-selection-overlay, .iwb-editor-cursor-overlay {\n position: absolute; top: 0; left: 0; display: block; pointer-events: none;\n background: transparent !important;\n}\n.iwb-editor-selection-overlay { z-index: 11; }\n.iwb-editor-cursor-overlay { z-index: 12; }\n\n/* ---- 选区浮动操作条(体验后再定去留;纯视图,可随时替换) ---- */\n.iwb-editor-sel-bar {\n display: none; position: absolute; z-index: 30; align-items: center; gap: 4px;\n padding: 5px 6px; background: rgba(24,24,37,0.96);\n border: 1px solid #45475a; border-radius: 8px;\n box-shadow: 0 8px 26px rgba(0,0,0,0.45); white-space: nowrap;\n}\n.iwb-editor-sel-bar.as-menu { border-color: #4488ff; }\n.iwb-editor-sel-bar .iwb-editor-sel-info {\n color: #7f849c; font-size: 11px; padding: 0 6px;\n border-right: 1px solid #45475a; margin-right: 2px; font-variant-numeric: tabular-nums;\n}\n.iwb-editor-sel-bar button {\n background: #313244; color: #cdd6f4; border: 1px solid transparent; border-radius: 5px;\n padding: 4px 8px; font-size: 12px; cursor: pointer;\n}\n.iwb-editor-sel-bar button:hover:not(:disabled) { background: #4488ff; color: #fff; }\n.iwb-editor-sel-bar button[data-sel-cmd="sel.delete"]:hover:not(:disabled) { background: #cf222e; }\n.iwb-editor-sel-bar button:disabled { opacity: 0.35; cursor: not-allowed; }\n\n/* ---- 状态栏 / toast ---- */\n.iwb-editor-statusbar {\n display: flex; align-items: center; gap: 14px;\n height: 26px; min-height: 26px; padding: 0 12px;\n background: #181825; border-top: 1px solid #313244;\n color: #a6adc8; font-size: 11px; font-variant-numeric: tabular-nums;\n}\n.iwb-editor-statusbar span + span { border-left: 1px solid #313244; padding-left: 14px; }\n.iwb-editor-status-tool { margin-left: auto; color: #e8a735; }\n.iwb-editor-toast {\n position: fixed; left: 50%; bottom: 46px; z-index: 1000000;\n transform: translate(-50%, 12px); opacity: 0; pointer-events: none;\n transition: opacity 0.2s, transform 0.2s;\n background: #313244; color: #cdd6f4; padding: 8px 14px; border-radius: 8px;\n font-size: 12px; max-width: 80vw; box-shadow: 0 8px 26px rgba(0,0,0,0.45);\n}\n.iwb-editor-toast.show { opacity: 1; transform: translate(-50%, 0); }\n.iwb-editor-toast-success { background: #1a7f37; color: #fff; }\n.iwb-editor-toast-error { background: #cf222e; color: #fff; }\n.iwb-editor-toast-warn { background: #b06a00; color: #fff; }\n.iwb-editor-toast-info { background: #2f6fed; color: #fff; }\n\n@media (max-width: 900px) {\n .iwb-opt-hint, .iwb-editor-optionbar-tip { display: none; }\n .iwb-editor-session .iwb-editor-btn-cancel,\n .iwb-editor-export-actions .iwb-editor-btn-cancel { display: none; }\n}\n\n\n/* 输出设置:按预设显示的行(尺寸/体积只属于电商方图)\n 注意 `.iwb-editor-export-row` 是 display:flex,会盖掉 UA 的 [hidden]{display:none},\n 必须显式 !important,否则 JS 设 hidden 后行还留在面板里。 */\n.iwb-editor-export-row[hidden] { display: none !important; }\n.iwb-editor-export-settings [data-export-key]:disabled {\n opacity: 0.32; cursor: not-allowed; text-decoration: line-through;\n}\n.iwb-editor-export-settings [data-export-key]:disabled:hover { background: #313244; }\n\n/* 选项栏参数控件(v1.2):滑杆 + 数字框 + 实时读数,一行放得下就该保持一行 */\n.iwb-opt-range {\n width: 84px; height: 4px; flex: 0 0 auto;\n accent-color: #4488ff; cursor: pointer;\n}\n.iwb-opt-val {\n min-width: 32px; flex: 0 0 auto; color: #e8a735; font-size: 11px;\n font-variant-numeric: tabular-nums; text-align: right;\n}\n.iwb-opt-unit { color: #7f849c; font-size: 11px; flex: 0 0 auto; }\n/* 窄屏:参数多到放不下时横向滚动,不换行(换行会把 36px 高的选项栏撑开压画布) */\n.iwb-editor-optionbar-body { overflow-x: auto; scrollbar-width: none; }\n.iwb-editor-optionbar-body::-webkit-scrollbar { display: none; }\n@media (max-width: 1100px) {\n .iwb-opt-range { width: 64px; }\n}\n\n/* ---- v1.2.2 ---- */\n/* 选项栏快捷值圆点(笔刷大小 / 矢量描边推荐值),与侧栏描边快捷点同交互 */\n.iwb-opt-dots { display: inline-flex; align-items: center; gap: 3px; flex: 0 0 auto; }\n.iwb-opt-dot {\n display: inline-flex; align-items: center; justify-content: center;\n width: 20px; height: 20px; padding: 0; border: 0; border-radius: 50%;\n background: transparent; cursor: pointer;\n}\n.iwb-opt-dot i { display: block; width: 5px; height: 5px; border-radius: 50%; background: #e8a735; border: 1px solid #f6d38a; }\n.iwb-opt-dot:nth-child(2) i { width: 7px; height: 7px; }\n.iwb-opt-dot:nth-child(3) i { width: 9px; height: 9px; }\n.iwb-opt-dot:nth-child(4) i { width: 11px; height: 11px; }\n.iwb-opt-dot:nth-child(5) i { width: 14px; height: 14px; }\n.iwb-opt-dot:nth-child(6) i { width: 17px; height: 17px; }\n.iwb-opt-dot:nth-child(7) i { width: 20px; height: 20px; }\n.iwb-opt-dot:hover { background: #313244; }\n\n/* 裁剪控件在选项栏内联布局(旧 .iwb-editor-crop-bar 的绝对定位容器已删除) */\n.iwb-editor-optionbar-body .iwb-editor-crop-info {\n min-width: 88px; text-align: center; color: #e8a735;\n font-size: 11px; font-variant-numeric: tabular-nums; flex: 0 0 auto;\n}\n.iwb-editor-optionbar-body .iwb-editor-size-input {\n width: 52px; padding: 2px 5px; font-size: 11px;\n background: #1e2030; color: #e5e9f0;\n border: 1px solid #45475a; border-radius: 4px;\n}\n.iwb-editor-optionbar-body .iwb-editor-size-input:focus { outline: none; border-color: #4488ff; }\n/* 硬度滑杆加宽:参数太密时默认 84px 拉不开,用户反馈「软度调节不明显」(2026-11-04) */\n.iwb-editor-optionbar-body .iwb-opt-range-wide { width: 140px; }\n.iwb-editor-optionbar-body .iwb-opt-dots { margin-left: 2px; }\n.iwb-editor-optionbar-body .iwb-editor-size-input::-webkit-inner-spin-button { -webkit-appearance: none; }\n.iwb-editor-optionbar-body .iwb-editor-crop-confirm,\n.iwb-editor-optionbar-body .iwb-editor-crop-cancel {\n padding: 3px 10px; border: 0; border-radius: 4px; cursor: pointer; font-size: 12px; flex: 0 0 auto;\n}\n.iwb-editor-optionbar-body .iwb-editor-crop-confirm { background: #1a7f37; color: #fff; }\n.iwb-editor-optionbar-body .iwb-editor-crop-confirm:hover { background: #15803d; }\n.iwb-editor-optionbar-body .iwb-editor-crop-cancel { background: #cf222e; color: #fff; }\n.iwb-editor-optionbar-body .iwb-editor-crop-cancel:hover { background: #b91c1c; }\n\n/* ---- v1.2.3:侧栏只留调色板 + 缩放 ---- */\n/* 笔刷粗细/快捷点从侧栏移除后,缩放条直接挂在 aside 下:贴底,与调色板拉开距离 */\n.iwb-editor-left > .iwb-editor-zoom { margin-top: auto; border-top: 1px solid #313244; padding-top: 10px; }\n\n/* ================================================================\n v1.2.4:顶栏命令带(原「更多 ▾」图标化)\n 布局:标题 | 撤销·重做·还原 | ⟨图层 新建/导入⟩ ⟨顺序 置顶/上移/下移/置底⟩ ⟨视图 适应/侧栏⟩ | …… | 输出·下载·新建·覆盖·退出\n ================================================================ */\n.iwb-editor-header > .iwb-editor-history { order: 1; }\n.iwb-editor-header > .iwb-editor-commands { order: 3; display: flex; align-items: center; gap: 6px; flex: 0 0 auto; }\n.iwb-editor-header > .iwb-editor-commands .iwb-editor-divider { width: 1px; height: 20px; background: #313244; flex: 0 0 auto; }\n.iwb-editor-cmdgroup { display: flex; align-items: center; gap: 4px; }\n.iwb-editor-cmdgroup[data-group="order"] { gap: 2px; }\n/* 顶栏里的命令按钮统一 30×30 方角,和撤销/重做同款 */\n.iwb-editor-header > .iwb-editor-commands .iwb-editor-action,\n.iwb-editor-header > .iwb-editor-commands .iwb-editor-layer-btn {\n width: 30px; height: 30px; min-width: 30px; padding: 0; border: 0; border-radius: 8px;\n background: #313244; color: #cdd6f4;\n display: inline-flex; align-items: center; justify-content: center; cursor: pointer;\n}\n.iwb-editor-header > .iwb-editor-commands .iwb-editor-action:hover:not(:disabled),\n.iwb-editor-header > .iwb-editor-commands .iwb-editor-layer-btn:hover:not(:disabled) { background: #45475a; }\n.iwb-editor-header > .iwb-editor-commands .iwb-editor-layer-btn:disabled { opacity: 0.35; cursor: not-allowed; }\n/* 选区命令(全选/反选/取消):v1.2.5 起放在「选择」工具的选项栏里,不再占竖工具条 */\n/* 分隔线只负责「分组」,不负责「推到右边」。\n 原来写的是 margin: 0 4px 0 auto —— auto 会把分隔线之后的内容整组推到最右侧,\n 在选项栏已经排满的情况下(文字样式那一行)直接把后面的选区按钮顶出可视区,\n 看起来就是「这个工具下没有那几个按钮」。留白交给末尾的 .iwb-opt-hint。 */\n.iwb-opt-sep { width: 1px; height: 18px; background: #313244; margin: 0 2px; flex: 0 0 auto; }\n.iwb-opt-selcmd {\n width: 26px; height: 26px; min-width: 26px; padding: 0; border: 0; border-radius: 7px;\n background: #26263a; color: #cdd6f4; flex: 0 0 auto;\n display: inline-flex; align-items: center; justify-content: center; cursor: pointer;\n}\n.iwb-opt-selcmd:hover { background: #45475a; }\n\n/* ================================================================\n v1.2.11:顶栏次序与配色(用户裁定 2026-11-04 晚)\n 布局:标题 | ⟨新建·覆盖·退出⟩ | 撤销·重做·还原 | 顺序·视图 | …… | 输出·导出\n 标题在前(它是标题,不能跑到按钮后面);会话组三键统一中性色,不再花\n ================================================================ */\n.iwb-editor-header > .iwb-editor-title { order: 0; }\n.iwb-editor-header > .iwb-editor-session { order: 1; display: flex; align-items: center; gap: 6px; flex: 0 0 auto; margin-left: 8px; }\n.iwb-editor-header > .iwb-editor-session .iwb-editor-btn { padding: 6px 10px; font-size: 11px; min-width: 56px; white-space: nowrap; }\n.iwb-editor-header > .iwb-editor-session .iwb-editor-btn-new,\n.iwb-editor-header > .iwb-editor-session .iwb-editor-btn-replace,\n.iwb-editor-header > .iwb-editor-session .iwb-editor-btn-cancel { background: #45475a; color: #cdd6f4; }\n.iwb-editor-header > .iwb-editor-session .iwb-editor-btn-new:hover,\n.iwb-editor-header > .iwb-editor-session .iwb-editor-btn-replace:hover,\n.iwb-editor-header > .iwb-editor-session .iwb-editor-btn-cancel:hover { background: #585b70; }\n/* 标题与会话组之间、撤销组与命令带之间的竖分隔 */\n.iwb-editor-header > .iwb-editor-session { margin-right: 4px; }\n.iwb-editor-header > .iwb-editor-divider { width: 1px; height: 20px; background: #313244; flex: 0 0 auto; margin: 0 4px; }\n\n/* ================================================================\n v1.3:色板搬进工具栏(用户裁定 2026-11-05)\n 工具栏最左一个「当前色圆点」,点开在工具栏上方弹出色板:\n [SV + 色相] | [吸管 + hex] | [6×2 推荐色]\n 弹层挂在 modal 下(不是工具栏里):工具栏 overflow-x:auto、\n canvas-wrap overflow:clip,放里面必被裁;位置由 events.js 按按钮矩形算。\n ================================================================ */\n.iwb-editor-modal { position: relative; }\n\n.iwb-editor-canvas-wrap > .iwb-editor-tools .iwb-editor-color-btn {\n width: 32px; height: 32px; min-width: 32px; flex: 0 0 auto; padding: 0;\n border: 0; border-radius: 9px; background: #313244; cursor: pointer;\n display: inline-flex; align-items: center; justify-content: center;\n}\n.iwb-editor-canvas-wrap > .iwb-editor-tools .iwb-editor-color-btn:hover,\n.iwb-editor-canvas-wrap > .iwb-editor-tools .iwb-editor-color-btn.active { background: #45475a; }\n.iwb-editor-color-btn i {\n width: 18px; height: 18px; border-radius: 50%; display: block; background: #ff4444;\n box-shadow: 0 0 0 2px #181825, 0 0 0 3px #585b70;\n}\n\n.iwb-editor-color-pop {\n position: absolute; z-index: 60; display: flex; align-items: center; gap: 10px;\n padding: 10px 12px; border-radius: 12px;\n background: rgba(24, 24, 37, 0.97); border: 1px solid #313244;\n box-shadow: 0 16px 40px rgba(0, 0, 0, 0.55);\n -webkit-backdrop-filter: blur(10px); backdrop-filter: blur(10px);\n}\n.iwb-editor-color-pop[hidden] { display: none; }\n.iwb-color-pop-picker { display: flex; gap: 8px; flex: 0 0 auto; }\n.iwb-editor-color-pop .iwb-color-sv { width: 180px; height: 104px; flex: 0 0 180px; }\n.iwb-editor-color-pop .iwb-color-hue { width: 16px; height: 104px; flex: 0 0 16px; }\n.iwb-color-pop-sep { width: 1px; align-self: stretch; background: #313244; flex: 0 0 auto; }\n.iwb-color-pop-fields { display: flex; align-items: center; gap: 6px; flex: 0 0 auto; }\n.iwb-editor-color-pop .iwb-editor-color-hex-input {\n width: 86px; height: 28px; padding: 0 6px; text-align: center;\n font: 600 12px monospace; border-radius: 6px; box-sizing: border-box;\n}\n.iwb-editor-color-pop .iwb-editor-color-swatches {\n display: grid; grid-template-columns: repeat(6, 22px); grid-auto-rows: 22px;\n gap: 7px; flex: 0 0 auto; align-content: center;\n}\n.iwb-editor-color-pop .iwb-editor-color-panel-swatch {\n width: 22px; height: 22px; padding: 0; border: 0; border-radius: 50%; cursor: pointer;\n transition: transform 0.08s ease;\n}\n.iwb-editor-color-pop .iwb-editor-color-panel-swatch:hover { transform: scale(1.12); }\n.iwb-editor-color-pop .iwb-editor-color-panel-swatch.active {\n outline: 2px solid #fff; outline-offset: 2px;\n}\n.iwb-editor-color-pop .iwb-editor-color-eye { width: 28px; height: 28px; border-radius: 6px; }\n\n/* ================================================================\n v1.4:侧栏「快速效果」\n 3×2 网格,作用于当前位图图层。只做颜色/采样变换,不改几何。\n 图标全部用 CSS 渐变画(不引第三方库,也不加 SVG 体积)。\n ================================================================ */\n.iwb-editor-fx {\n display: flex; flex-direction: column; gap: 8px;\n flex: 0 0 auto;\n}\n.iwb-editor-fx-head {\n display: flex; align-items: center; justify-content: space-between; gap: 6px;\n}\n.iwb-editor-fx-title {\n font-size: 11px; font-weight: 600; letter-spacing: 0.4px; color: #a6adc8;\n}\n.iwb-editor-fx-target {\n max-width: 116px; overflow: hidden; text-overflow: ellipsis; white-space: nowrap;\n padding: 2px 6px; border-radius: 5px; background: #313244; color: #cdd6f4;\n font-size: 10px; line-height: 1.4;\n}\n.iwb-editor-fx-grid {\n display: grid; grid-template-columns: repeat(3, 1fr); gap: 6px;\n}\n.iwb-editor-fx-btn {\n display: flex; flex-direction: column; align-items: center; gap: 5px;\n padding: 7px 2px 6px; border: 1px solid transparent; border-radius: 9px;\n background: #232334; color: #cdd6f4;\n font: 500 10.5px/1 -apple-system, BlinkMacSystemFont, "PingFang SC", sans-serif;\n cursor: pointer; transition: background 0.12s ease, border-color 0.12s ease, transform 0.08s ease;\n}\n.iwb-editor-fx-btn:hover { background: #313244; border-color: #45475a; }\n.iwb-editor-fx-btn:active { transform: scale(0.96); }\n.iwb-editor-fx-btn:focus-visible { outline: 2px solid #89b4fa; outline-offset: 1px; }\n/* v1.8:当前生效的效果。必须与 hover 一眼区分 —— 拖动强度滑杆时要能看出在调哪个效果 */\n.iwb-editor-fx-btn.is-active {\n background: #2c2735; border-color: #e8a735; color: #f3dcb0;\n}\n.iwb-editor-fx-btn.is-active .iwb-editor-fx-ico {\n box-shadow: inset 0 0 0 1px rgba(232, 167, 53, 0.75);\n}\n.iwb-editor-fx-ico {\n width: 22px; height: 22px; border-radius: 5px; display: block;\n background-color: #d9d9e3;\n box-shadow: inset 0 0 0 1px rgba(255, 255, 255, 0.2);\n}\n/* 图标统一垫浅色底:纯黑部分若直接压在深色按钮上会「消失」,看着像缺了个角 */\n.ico-invert { background-image: linear-gradient(135deg, transparent 0 50%, #14141f 50% 100%); }\n.ico-gray { background-image: linear-gradient(90deg, #12121c 0, #8a8a99 50%, #f4f4f8 100%); }\n.ico-boost {\n background-image: radial-gradient(circle at 50% 52%, #ffffff 0 24%, #cfcfdd 42%, #6e6e85 100%);\n}\n.ico-contrast { background-image: linear-gradient(90deg, #000000 0 46%, #ffffff 54% 100%); }\n.ico-soft {\n background-image: radial-gradient(circle at 50% 50%, #23233a 0 16%, rgba(35, 35, 58, 0.5) 34%, rgba(35, 35, 58, 0.16) 50%, rgba(35, 35, 58, 0) 68%);\n}\n.ico-mosaic {\n background-image: repeating-conic-gradient(#6b6b80 0% 25%, #d9d9e3 0% 50%);\n background-size: 10px 10px;\n}\n.iwb-editor-fx-tip {\n margin: 0; font-size: 10px; line-height: 1.55; color: #6c7086;\n}\n\n/* v1.8:效果参数滑杆。范围与单位随效果切换(马赛克=块大小 px、柔化=半径 px、其余=强度 %)。\n 未点效果 / 目标层被切走时加 .iwb-editor-fx-adj-off 整条置灰。 */\n.iwb-editor-fx-adj {\n display: flex; flex-direction: column; gap: 4px;\n padding: 6px 8px 5px; border-radius: 7px;\n background: #1e1e2c; border: 1px solid #2f2f42;\n transition: opacity 0.12s ease;\n}\n.iwb-editor-fx-adj-head {\n display: flex; align-items: center; justify-content: space-between; gap: 6px;\n}\n.iwb-editor-fx-adj-name {\n font-size: 10.5px; font-weight: 500; color: #b9c0d8;\n overflow: hidden; text-overflow: ellipsis; white-space: nowrap;\n}\n.iwb-editor-fx-adj-val {\n font-size: 10.5px; color: #e8a735; font-variant-numeric: tabular-nums; flex: 0 0 auto;\n}\n.iwb-editor-fx-adj-off { opacity: 0.5; }\n.iwb-editor-fx-range {\n -webkit-appearance: none; appearance: none;\n width: 100%; height: 14px; margin: 0; background: transparent; cursor: pointer;\n}\n.iwb-editor-fx-range::-webkit-slider-runnable-track { height: 4px; border-radius: 2px; background: #313244; }\n.iwb-editor-fx-range::-webkit-slider-thumb {\n -webkit-appearance: none; appearance: none;\n width: 12px; height: 12px; margin-top: -4px; border-radius: 50%;\n background: #e8a735; border: 1px solid #1e1e2c;\n box-shadow: 0 1px 2px rgba(0, 0, 0, 0.45);\n}\n.iwb-editor-fx-range::-moz-range-track { height: 4px; border-radius: 2px; background: #313244; }\n.iwb-editor-fx-range::-moz-range-thumb {\n width: 12px; height: 12px; border-radius: 50%; background: #e8a735; border: 1px solid #1e1e2c;\n}\n.iwb-editor-fx-range:disabled { cursor: default; }\n.iwb-editor-fx-range:disabled::-webkit-slider-thumb { background: #585b70; }\n.iwb-editor-fx-range:disabled::-moz-range-thumb { background: #585b70; }\n.iwb-editor-fx-range:focus-visible { outline: 2px solid #89b4fa; outline-offset: 2px; }\n\n/* ================================================================\n v1.6:图层面板多选(⌘/Ctrl 点击)+ 合并按钮\n 多选用青色侧条与单选(橙色 #e8a735)区分:一个图层可以「被选中但不在合并集合里」,\n 两套状态不能长得一样。\n ================================================================ */\n.iwb-layer-item.multi {\n background: rgba(137, 180, 250, 0.14);\n box-shadow: inset 2px 0 0 #89b4fa;\n}\n.iwb-layer-item.multi.active {\n background: rgba(137, 180, 250, 0.2);\n box-shadow: inset 2px 0 0 #89b4fa, inset 0 0 0 1px rgba(137, 180, 250, 0.45);\n}\n.iwb-editor-layer-add-group { flex: 0 0 auto; flex-wrap: nowrap; }\n.iwb-editor-layer-add-btn[data-action="mergeLayers"]:hover,\n.iwb-editor-layer-add-btn[data-action="mergeVisible"]:hover {\n background: #45475a;\n border-color: #89b4fa;\n color: #cdd6f4;\n}\n\n/* ================================================================\n v1.9:文字样式控件 / 圆角 / 最近使用颜色 / 复制按钮\n ================================================================ */\n\n/* 选项栏里的原生颜色框(描边色 / 底色):压成和数字框同高的小方块 */\n.iwb-opt-color {\n width: 22px;\n height: 20px;\n padding: 0;\n flex: 0 0 auto;\n border: 1px solid #45475a;\n border-radius: 4px;\n background: transparent;\n cursor: pointer;\n}\n.iwb-opt-color::-webkit-color-swatch-wrapper { padding: 2px; }\n.iwb-opt-color::-webkit-color-swatch { border: 0; border-radius: 3px; }\n\n/* 「最近使用」:色板弹层里 4 列 × 2 行,空的时候整块隐藏(不占位) */\n.iwb-editor-color-pop .iwb-editor-recent-colors {\n display: grid;\n grid-template-columns: repeat(4, 18px);\n grid-auto-rows: 18px;\n gap: 5px;\n flex: 0 0 auto;\n align-content: center;\n}\n.iwb-editor-recent-colors[hidden] { display: none; }\n.iwb-editor-color-pop .iwb-editor-recent-colors .iwb-editor-color-panel-swatch {\n width: 18px;\n height: 18px;\n padding: 0;\n border: 0;\n border-radius: 50%;\n cursor: pointer;\n}\n.iwb-editor-color-pop .iwb-editor-recent-colors .iwb-editor-color-panel-swatch:hover { transform: scale(1.12); }\n\n/* 复制到剪贴板:与「导出」同尺寸但用低饱和色,避免两个绿色按钮抢眼 */\n.iwb-editor-btn-copy { background: #313244 !important; color: #cdd6f4 !important; }\n.iwb-editor-btn-copy:hover { background: #3b3d52 !important; }\n\n/* 选项栏按钮里是中文双字标签(常规/特粗/底色),不给 nowrap 会被挤成竖排 */\n.iwb-editor-optionbar-body .iwb-opt-btn { white-space: nowrap; }\n';
// image-annotate/plugin/glue.js
function createGlue(ctx, css) {
let styleInjected = false;
function ensureStyle() {
if (styleInjected) return;
styleInjected = true;
try {
const style = document.createElement("style");
style.id = "iwb-annotate-style";
style.textContent = css;
(document.head || document.documentElement).appendChild(style);
} catch (error) {
styleInjected = false;
ctx.log("inject-style-failed", error && error.message);
}
}
function blobToDataUrl(blob) {
return new Promise(function(resolve, reject) {
const reader = new FileReader();
reader.onload = function() {
resolve(String(reader.result || ""));
};
reader.onerror = function() {
reject(reader.error || new Error("读取导出图片失败"));
};
reader.readAsDataURL(blob);
});
}
function imageToDataUrl(out) {
if (typeof out === "string") return Promise.resolve(out);
if (out && typeof out.arrayBuffer === "function") return blobToDataUrl(out);
return Promise.reject(new Error("导出结果不是可用的图片数据"));
}
function baseName(node) {
return String(node && node.name || "image").replace(/\.[^.]+$/, "") || "image";
}
function openEditor(node) {
const id = node && node.id;
if (!id) return Promise.reject(new Error("请先选中一个带图的节点"));
const editor = typeof window !== "undefined" ? window.__iwbEditor : null;
if (!editor || typeof editor.open !== "function") {
return Promise.reject(new Error("标注编辑器未加载"));
}
return Promise.resolve(ctx.canvas.getNodeImage(id)).then(function(image) {
if (!image || !image.dataUrl) {
throw new Error(image && image.url ? "该节点是远程图片,暂不支持标注(请先转存为本地位图)" : "该节点没有可编辑的图片");
}
ensureStyle();
return new Promise(function(resolve, reject) {
let settled = false;
let handedOff = false;
const settle = function(fn) {
if (!settled) {
settled = true;
fn();
}
};
Promise.resolve(editor.open({
imageBase64: image.dataUrl,
imageName: baseName(node) + ".png",
settings: ctx.settings,
// 记住输出预设 / 侧栏开合(宿主提供的命名空间 KV)
onError: function(message) {
settle(function() {
reject(new Error(String(message || "编辑失败")));
});
},
onClose: function() {
if (handedOff) return;
settle(function() {
resolve("cancel");
});
},
onResult: function(out, mode) {
handedOff = true;
imageToDataUrl(out).then(function(dataUrl) {
const replaced = mode === "replace";
const ok = replaced ? ctx.canvas.setNodeImage(id, dataUrl) : Boolean(ctx.canvas.createImageNode({ dataUrl, name: baseName(node) + "_edit.png" }));
if (!ok) throw new Error(replaced ? "写回原节点失败" : "新建节点失败");
settle(function() {
resolve(mode);
});
}).catch(function(error) {
settle(function() {
reject(error);
});
});
}
})).catch(function(error) {
settle(function() {
reject(error);
});
});
});
});
}
function appliesTo(node) {
if (!node) return false;
return node.type === "ref";
}
ctx.nodeActions.register({
id: "annotate-node",
title: "标注 / 修图",
icon: "pencil-ruler",
appliesTo,
run: function(node) {
return openEditor(node);
}
});
ctx.commands.register({
id: "annotate-selected",
title: "标注 / 修图:选中节点",
icon: "pencil-ruler",
run: function() {
const selected = ctx.canvas.getSelectedNode();
if (!selected) return Promise.reject(new Error("请先选中一个带图的节点"));
return openEditor(selected);
}
});
return {
dispose: function() {
}
};
}
// image-annotate/plugin/entry.js
(typeof window !== "undefined" ? window : globalThis).__IWB_ANNOTATE_FACTORY__ = function(ctx) {
return createGlue(ctx, editor_default);
};
})();
// 手写注册尾部(build-plugin.mjs 原样追加到产物末尾,不 overlapped with esbuild 的打印器)。
// 时序:bundle 先执行(挂好 __IWB_ANNOTATE_FACTORY__),再注册;factory 由宿主在「启用插件」时才调用。
;(function (global) {
'use strict'
if (!global.IWBPluginHost) return
global.IWBPluginHost.register(__IWB_ANNOTATE_MANIFEST__, function (ctx) {
return global.__IWB_ANNOTATE_FACTORY__(ctx)
})
})(typeof window !== 'undefined' ? window : globalThis)