Files
iwb-plugins-desktop/image-annotate/src/index.js
T

5982 lines
277 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.1.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,
// 吸管工具激活前的工具(取色后切回)
pickerComposite: null,
// 吸管取样用的合成画布缓存(切工具/画布变化时失效)
rectFill: false,
// 矩形是否实心填充
// 图层系统
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,
// 选择工具当前选中的可编辑位图图层
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 注入的统一重绘出口
lastExport: null
// 观测口:{ bytes, width, height, format, preset }
};
var runtime = { el: null };
// 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 / S.zoom;
ctx.setLineDash([8 / S.zoom, 4 / S.zoom]);
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 = 8 / S.zoom;
ctx.fillStyle = "#fff";
ctx.strokeStyle = "#4488ff";
ctx.lineWidth = 1.5 / S.zoom;
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 / S.zoom) + "px sans-serif";
ctx.textAlign = "center";
ctx.textBaseline = "top";
const hintText = "拖拽手柄调整大小 · 圆点=旋转 · Shift=等比/15°吸附 · Enter=确认 · Esc=取消";
const br = boxCorners(x, y, w, h, rot).reduce((acc, pt) => Math.max(acc, pt[1]), -Infinity);
const hintY = br + 10 / S.zoom;
const tw = ctx.measureText(hintText).width;
ctx.fillStyle = "rgba(0,0,0,0.6)";
ctx.fillRect(cx - tw / 2 - 6 / S.zoom, hintY, tw + 12 / S.zoom, 22 / S.zoom);
ctx.fillStyle = "rgba(255,255,255,0.95)";
ctx.fillText(hintText, cx, hintY + 4 / S.zoom);
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 / S.zoom;
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/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 / S.zoom;
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;
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 = 7 / S.zoom;
ctx.save();
ctx.strokeStyle = "#e8a735";
ctx.lineWidth = 1.5 / S.zoom;
ctx.setLineDash([6 / S.zoom, 3 / S.zoom]);
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") {
layer.x = base.x + pos.x - drag.start.x;
layer.y = base.y + pos.y - drag.start.y;
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) {
S.activeLayerId = id;
selectUnit("bitmap", id);
renderLayerPanel();
renderObjects();
}
function addBitmapLayer(img) {
placeImageDirectly(img);
}
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 {
ctx.save();
ctx.textBaseline = "top";
ctx.globalAlpha = obj.opacity != null ? obj.opacity : 1;
const rot = obj.rotation || 0;
if (rot) {
const b = textBounds(obj);
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.font = TEXT_FONT(obj.fontSize);
ctx.fillStyle = obj.color;
ctx.fillText(obj.text, obj.x, obj.y);
ctx.restore();
}
}
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";
}
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 renderLayerPanel() {
const list = runtime.el.querySelector(".iwb-editor-layer-list");
if (!list) return;
const items = [];
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,
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,
paintTarget: false,
locked: !!obj.locked,
canDelete: true
});
}
}
let html = "";
for (const item of items) {
const activeClass = item.active ? " active" : "";
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>';
html += `<div class="iwb-layer-item${activeClass}${visClass}" draggable="${item.id !== "base"}" data-layer-id="${item.id}" data-layer-type="${item.type}">
<button class="iwb-layer-vis" data-vis-id="${item.id}" data-vis-type="${item.type}" title="${item.visible ? "隐藏" : "显示"}">${visSvg}</button>
<span class="iwb-layer-icon">${typeIconSvg}</span>
<span class="iwb-layer-name">${item.name}</span>${item.paintTarget ? '<span class="iwb-layer-paint" title="当前画笔 / 橡皮作用图层">✎</span>' : ""}
${item.type === "bitmap" || item.type === "shape" ? `<input class="iwb-layer-color" type="color" value="${item.color}" data-color-id="${item.id}" data-color-type="${item.type}" title="调整颜色">` : ""}
${item.type === "bitmap" || item.type === "shape" ? `<input class="iwb-layer-width" type="number" min="1" max="300" value="${Math.round(item.lineWidth)}" data-width-id="${item.id}" data-width-type="${item.type}" title="调整边框粗细">` : ""}
<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>`;
}
list.innerHTML = html;
bindLayerPanelEvents();
}
function reorderPanelItem(dragId, targetId) {
if (!dragId || !targetId || dragId === targetId || dragId === "base" || targetId === "base") return;
const all = layerUnits();
const baseIdx = all.findIndex((u) => u.obj.id === "base");
if (baseIdx > 0) {
const [b] = all.splice(baseIdx, 1);
all.unshift(b);
}
const from = all.findIndex((item) => item.obj.id === dragId);
const to0 = all.findIndex((item) => item.obj.id === targetId);
if (from < 0 || to0 < 0) return;
const before = all.map((u) => u.obj.id).join("|");
const [moved] = all.splice(from, 1);
const to = Math.max(all.findIndex((item) => item.obj.id === targetId), baseIdx >= 0 ? 1 : 0);
all.splice(to, 0, moved);
if (all.map((u) => u.obj.id).join("|") === before) return;
saveSnapshot();
assignLayerZ(all);
reorderLayerCanvas();
sortLayersByZ();
renderObjects();
renderLayerPanel();
}
function bindLayerPanelEvents() {
const list = runtime.el.querySelector(".iwb-editor-layer-list");
if (!list) return;
bindLayerItemEvents(list);
bindLayerStyleInputs(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("dragstart", (e) => {
if (item.draggable) {
e.dataTransfer.setData("text/plain", item.dataset.layerId);
item.classList.add("dragging");
}
});
item.addEventListener("dragend", () => item.classList.remove("dragging"));
item.addEventListener("dragover", (e) => {
if (item.draggable) e.preventDefault();
});
item.addEventListener("drop", (e) => {
e.preventDefault();
reorderPanelItem(e.dataTransfer.getData("text/plain"), item.dataset.layerId);
});
item.addEventListener("click", (e) => {
if (e.target.closest(".iwb-layer-vis") || e.target.closest(".iwb-layer-lock") || e.target.closest(".iwb-layer-del")) return;
const id = item.dataset.layerId;
const type = item.dataset.layerType;
if (type === "bitmap") {
setActiveLayer(id);
} else if (type === "text" || type === "shape") {
selectUnit(type, id);
renderObjects();
renderLayerPanel();
}
});
});
}
function bindLayerStyleInputs(list) {
list.querySelectorAll(".iwb-layer-color").forEach((input) => {
input.addEventListener("mousedown", (e) => e.stopPropagation());
input.addEventListener("input", (e) => {
e.stopPropagation();
const id = input.dataset.colorId;
const type = input.dataset.colorType;
const obj = type === "bitmap" ? S.layers.find((l) => l.id === id) : S.shapeLayers.find((s) => s.id === id);
if (obj) {
obj.color = input.value;
S.color = input.value;
updateColorUI();
renderObjects();
renderLayerPanel();
S.pickerComposite = null;
}
});
});
list.querySelectorAll(".iwb-layer-width").forEach((input) => {
input.addEventListener("mousedown", (e) => e.stopPropagation());
input.addEventListener("input", (e) => {
e.stopPropagation();
const id = input.dataset.widthId;
const type = input.dataset.widthType;
const value = clamp(parseInt(input.value, 10) || 1, 1, 300);
const obj = type === "bitmap" ? S.layers.find((l) => l.id === id) : S.shapeLayers.find((s) => s.id === id);
if (obj) {
obj.lineWidth = value;
if (type === "shape") obj.lw = value;
else S.brushSize = value;
renderObjects();
updateBrushParamUI();
renderLayerPanel();
}
});
});
}
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();
}
});
});
}
// 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/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;
const pad = S.overlayPad || 0;
ctx.save();
ctx.setTransform(1, 0, 0, 1, 0, 0);
ctx.clearRect(0, 0, S.imgW + pad * 2, S.imgH + pad * 2);
ctx.restore();
ctx.setTransform(1, 0, 0, 1, pad, pad);
}
function clearCursorCanvas() {
const ctx = S.cursorCtx;
if (!ctx) return;
const pad = S.overlayPad || 0;
ctx.save();
ctx.setTransform(1, 0, 0, 1, 0, 0);
ctx.clearRect(0, 0, S.imgW + pad * 2, S.imgH + pad * 2);
ctx.restore();
ctx.setTransform(1, 0, 0, 1, pad, pad);
}
function renderSelection() {
if (!S.selectionCtx) return;
clearSelectionCanvas();
const ctx = S.selectionCtx;
const k = 1 / Math.max(S.zoom, 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 = writableLayer();
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>
<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"><polyline points="3 6 5 6 21 6"/><path d="M19 6v14a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2V6m3 0V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2"/></svg></button>
</div>
<div class="iwb-editor-more-wrap">
<button class="iwb-editor-more-btn" data-action="toggleMore" aria-expanded="false">更多 ▾</button>
<div class="iwb-editor-more-menu">
<button data-more="sel.all">全选 <kbd>Ctrl+A</kbd></button>
<button data-more="sel.invert">反选 <kbd>Ctrl+Shift+I</kbd></button>
<button data-more="sel.none">取消选区 <kbd>Esc</kbd></button>
<span class="iwb-editor-more-sep"></span>
<button data-more="addBlankLayer">新建空白图层</button>
<button data-more="addBitmapLayer">导入图片为图层</button>
<button data-more="zoomFit">适应窗口</button>
<button data-more="reset">还原原图</button>
<span class="iwb-editor-more-sep"></span>
<button data-action="togglePanels">收起 / 展开侧栏</button>
</div>
</div>
<button class="iwb-editor-panel-toggle" data-action="togglePanels" title="收起 / 展开侧栏(画布优先)">⇥</button>
<div class="iwb-editor-tools">
<button class="iwb-editor-tool" data-tool="select" title="选择/移动:点击元素选中,拖拽移动,手柄调整大小,双击文字改内容"><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>
<button class="iwb-editor-tool" data-tool="marquee" title="框选:拖出矩形/椭圆选区,松手后旁边出现操作条(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="画笔"><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="橡皮:擦除当前活跃图层的内容(画笔标注或原图),与画笔共用大小/硬度/透明度"><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="钢笔:点击添加节点,双击或 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="文字"><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="矩形框"><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="圆形"><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="箭头"><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="吸管:点击画布取色(悬停预览),取色后自动切回上一工具"><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="抓手:拖拽自由移动画布(任意工具下按住空格或鼠标中键也可平移)"><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="裁剪"><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>
<button class="iwb-editor-fill-btn" data-action="toggleFill" title="矩形实心填充开关(选中矩形时切换即时生效)">实心</button>
</div>
<span class="iwb-editor-divider"></span>
<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">电商 800² ≤500KB</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-note">一次只输出一个结果;设置会记住</div>
</div>
</div>
<button class="iwb-editor-btn iwb-editor-btn-download" data-action="download" title="下载当前这一张(不关闭编辑器)">下载</button>
<button class="iwb-editor-btn iwb-editor-btn-new" data-action="newNode">新建</button>
<button class="iwb-editor-btn iwb-editor-btn-replace" data-action="replace">覆盖</button>
<button class="iwb-editor-btn iwb-editor-btn-cancel" data-action="cancel">退出</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">选区操作也可以右键,或用 Ctrl+J / Delete / Esc</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>
<div class="iwb-editor-layer-add-group">
<button class="iwb-editor-layer-add-btn" data-action="addBitmapLayer" title="导入图片为新图层(也可直接 ⌘/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>
<button class="iwb-editor-layer-add-btn" data-action="addBlankLayer" title="新建空白图层"><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>
</div>
</div>
<div class="iwb-editor-layer-group" title="调整选中元素的图层顺序">
<span class="iwb-editor-constraint-label">图层</span>
<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>
<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>
<input class="iwb-editor-text-input" type="text" placeholder="输入文字,Enter确认,Esc取消">
<div class="iwb-editor-picker-tip"><span class="iwb-editor-picker-chip"></span><span class="iwb-editor-picker-hex">#ffffff</span></div>
<div class="iwb-editor-crop-bar">
<div class="iwb-editor-crop-row"><div class="iwb-editor-constraint-group">
<span class="iwb-editor-constraint-label">比例</span>
<button class="iwb-editor-constraint-btn active" data-ratio="free">自由</button>
<button class="iwb-editor-constraint-btn" data-ratio="1:1">1:1</button>
<button class="iwb-editor-constraint-btn" data-ratio="4:3">4:3</button>
<button class="iwb-editor-constraint-btn" data-ratio="3:4">3:4</button>
<button class="iwb-editor-constraint-btn" data-ratio="16:9">16:9</button>
<button class="iwb-editor-constraint-btn" data-ratio="9:16">9:16</button>
</div></div>
<div class="iwb-editor-crop-row"><div class="iwb-editor-constraint-group">
<span class="iwb-editor-constraint-label">尺寸</span>
<input class="iwb-editor-size-input iwb-editor-size-w" type="number" min="1" placeholder="宽" value="800">
<span class="iwb-editor-size-x">×</span>
<input class="iwb-editor-size-input iwb-editor-size-h" type="number" min="1" placeholder="高" value="800">
<button class="iwb-editor-constraint-btn iwb-editor-size-toggle" data-action="toggleSizeConstraint" aria-pressed="false">启用尺寸</button>
<button class="iwb-editor-constraint-btn iwb-editor-size-apply" data-action="applySize">应用</button>
</div></div>
<div class="iwb-editor-crop-row iwb-editor-crop-actions"><span class="iwb-editor-crop-info">--</span>
<button class="iwb-editor-crop-confirm" data-action="confirmCrop">✓ 确认</button>
<button class="iwb-editor-crop-cancel" data-action="cancelCrop">✗ 取消</button>
</div>
</div>
<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>
<div class="iwb-editor-zoom-hint">滚轮缩放 · 抓手/空格/中键拖拽自由移动画布</div>
<aside class="iwb-editor-left">
<div class="iwb-editor-color-panel"><div class="iwb-editor-color-panel-title">调色板</div><div class="iwb-editor-color-picker2"><div class="iwb-color-sv"><span></span></div><div class="iwb-color-hue"><span></span></div></div><div class="iwb-editor-color-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"></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="#ff8800" style="background:#ff8800" title="#ff8800"></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="#44dd44" style="background:#44dd44" title="#44dd44"></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="#b8b8b8" style="background:#b8b8b8" title="#b8b8b8"></button><button type="button" class="iwb-editor-color-panel-swatch" data-panel-color="#555555" style="background:#555555" title="#555555"></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-params">
<label class="iwb-editor-brush-label">描边
<input type="range" class="iwb-editor-brush-size" min="1" max="300" value="3">
<input type="number" class="iwb-editor-brush-num" min="1" max="300" step="1" value="3" title="输入精确笔刷大小(1~300)">
</label>
<div class="iwb-editor-brush-presets" aria-label="描边快捷值">
<button type="button" class="iwb-editor-brush-preset" data-brush-size="2" title="描边 2"><i></i></button>
<button type="button" class="iwb-editor-brush-preset" data-brush-size="4" title="描边 4"><i></i></button>
<button type="button" class="iwb-editor-brush-preset" data-brush-size="8" title="描边 8"><i></i></button>
<button type="button" class="iwb-editor-brush-preset" data-brush-size="12" title="描边 12"><i></i></button>
<button type="button" class="iwb-editor-brush-preset" data-brush-size="16" title="描边 16"><i></i></button>
<button type="button" class="iwb-editor-brush-preset" data-brush-size="24" title="描边 24"><i></i></button>
<button type="button" class="iwb-editor-brush-preset" data-brush-size="32" title="描边 32"><i></i></button>
</div>
<div class="iwb-editor-brush-group">
<label class="iwb-editor-brush-label">硬度
<input type="range" class="iwb-editor-brush-hardness" min="0" max="100" value="100">
<span class="iwb-editor-brush-hardness-val">100</span>
</label>
<label class="iwb-editor-brush-label iwb-editor-opacity-label">透明
<input type="range" class="iwb-editor-brush-opacity" min="5" max="100" step="5" value="100">
<span class="iwb-editor-brush-opacity-val">100%</span>
</label>
</div>
</div>
<div class="iwb-editor-zoom">
<button class="iwb-editor-zoom-btn" data-action="zoomOut" title="缩小 (滚轮向下)">−</button>
<span class="iwb-editor-zoom-val" title="滚轮缩放">100%</span>
<button class="iwb-editor-zoom-btn" data-action="zoomIn" title="放大 (滚轮向上)">+</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>
<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/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/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.tool === "marquee") {
beginMarquee(pos);
return;
}
if (S.tool === "lasso") {
beginLasso(pos);
return;
}
if (S.tool === "select" || S.tool === "pen") {
const penShape = getPenEditingShape();
if (penShape && onPenEditMouseDown(e, pos, penShape)) return;
}
const handler = Object.prototype.hasOwnProperty.call(MOUSE_DOWN_HANDLERS, S.tool) ? MOUSE_DOWN_HANDLERS[S.tool] : null;
if (handler) handler(pos);
}
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 / S.zoom, 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;
const handle = hitTextHandle(pos);
if (handle) {
if (handle === "rotate") beginTextRotate(pos);
else beginTextScaleDrag(handle, pos);
return;
}
const hit = hitTextLayer(pos);
if (hit) {
selectUnit("text", hit.id);
if (hit.locked) {
renderObjects();
renderLayerPanel();
return;
}
S.textDrag = {
mode: "move",
start: pos,
layer: { x: hit.x, y: hit.y },
pending: snapshotState()
};
renderObjects();
renderLayerPanel();
} else {
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) {
if (!getActiveCtx()) return;
S.isDrawing = true;
saveSnapshot();
beginStroke();
strokeSegment(pos.x, pos.y, pos.x, pos.y);
}
function onEraserMouseDown(pos) {
if (!getActiveCtx()) return;
S.isDrawing = true;
saveSnapshot();
beginStroke();
eraseSegment(pos.x, pos.y, pos.x, pos.y);
}
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 / S.zoom, S.brushSize * 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(2, S.brushSize), fill: false, opacity: 1, visible: true });
}
return;
}
function onShapeMouseDown(pos) {
const handle = hitShapeHandle(pos);
if (handle) {
beginShapeHandleDrag(handle, pos);
return;
}
const hitShape = hitShapeLayer(pos, true);
if (hitShape && hitShape.type === S.tool) {
S.selectedShapeId = hitShape.id;
if (hitShape.locked) {
renderObjects();
renderLayerPanel();
return;
}
S.shapeDrag = { mode: "move", start: pos, shape: { ...hitShape }, pending: snapshotState() };
renderObjects();
renderLayerPanel();
return;
}
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) {
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;
t.x = clamp(S.textDrag.layer.x + dx, 0, Math.max(0, S.imgW - 4));
t.y = clamp(S.textDrag.layer.y + dy, 0, Math.max(0, S.imgH - 4));
} 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);
const cdx = clamp(dx, -b.x, Math.max(-b.x, S.imgW - (b.x + b.w)));
const cdy = clamp(dy, -b.y, Math.max(-b.y, S.imgH - (b.y + b.h)));
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 / S.zoom, S.brushSize * 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(2, S.brushSize),
lineWidth: Math.max(2, S.brushSize),
fill: S.tool === "rect" || S.tool === "circle" ? !!S.rectFill : false,
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;
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;
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;
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(2, S.brushSize),
fill: S.tool === "rect" || S.tool === "circle" ? !!S.rectFill : false,
opacity: 1,
visible: true,
locked: false,
z: ++S.zCounter
};
S.shapeLayers.push(shape);
selectUnit("shape", shape.id);
}
renderObjects();
renderLayerPanel();
}
function onWheel(e) {
if (!S.open) 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 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");
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();
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() {
const slider = runtime.el.querySelector(".iwb-editor-brush-size");
if (!slider) return;
slider.value = S.brushSize;
const num = runtime.el.querySelector(".iwb-editor-brush-num");
if (num && document.activeElement !== num) num.value = S.brushSize;
}
function updateBrushParamUI() {
const g = runtime.el.querySelector(".iwb-editor-brush-group");
if (!g) return;
g.style.display = S.tool === "brush" || S.tool === "eraser" ? "flex" : "none";
const oLabel = g.querySelector(".iwb-editor-opacity-label");
if (oLabel) oLabel.style.display = S.tool === "brush" || S.tool === "eraser" ? "" : "none";
const h = g.querySelector(".iwb-editor-brush-hardness");
if (h) {
h.value = S.brushHardness;
g.querySelector(".iwb-editor-brush-hardness-val").textContent = S.brushHardness;
}
const o = g.querySelector(".iwb-editor-brush-opacity");
if (o) {
o.value = Math.round(S.brushOpacity * 100);
g.querySelector(".iwb-editor-brush-opacity-val").textContent = Math.round(S.brushOpacity * 100) + "%";
}
}
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: "裁剪"
};
function renderOptionBar() {
const body = runtime.el && runtime.el.querySelector(".iwb-editor-optionbar-body");
if (!body) return;
let html = "";
if (S.tool === "marquee") {
html = `<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">拖出选区 → 操作条就在选区旁边</span>`;
} else if (S.tool === "lasso") {
html = `<span class="iwb-opt-label">套索</span>
<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">按住拖动画圈,松手闭合</span>`;
} else {
const hints = {
crop: "裁剪栏在画布下方;裁剪与选区互斥",
brush: "选区激活时笔刷只画在选区内",
eraser: "橡皮只擦当前画笔目标图层(✎)",
select: "点击选中元素,拖拽移动,手柄缩放"
};
html = `<span class="iwb-opt-current">当前工具:${TOOL_NAMES[S.tool] || S.tool}</span>
<span class="iwb-opt-hint">${hints[S.tool] || "选区工具按 M / L;Ctrl+J 复制选区,Delete 清除当前层"}</span>`;
}
body.innerHTML = html;
}
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);
}
function bindLiteUI() {
const root = runtime.el;
if (!root || root.dataset.liteBound === "1") return;
root.dataset.liteBound = "1";
const moreBtn = root.querySelector('[data-action="toggleMore"]');
const moreMenu = root.querySelector(".iwb-editor-more-menu");
const closeMenus = () => {
if (moreMenu) moreMenu.classList.remove("open");
if (moreBtn) moreBtn.setAttribute("aria-expanded", "false");
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");
};
if (moreBtn && moreMenu) {
moreBtn.addEventListener("mousedown", (e) => e.stopPropagation());
moreBtn.addEventListener("click", (e) => {
e.stopPropagation();
const open2 = moreMenu.classList.toggle("open");
moreBtn.setAttribute("aria-expanded", String(open2));
});
}
if (moreMenu) {
moreMenu.addEventListener("mousedown", (e) => e.stopPropagation());
moreMenu.addEventListener("click", (e) => {
const btn = e.target.closest("button");
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 === "addBitmapLayer") {
const b = root.querySelector('.iwb-editor-layer-add-btn[data-action="addBitmapLayer"]');
if (b) b.click();
} else if (key === "zoomFit") setZoomFit();
else if (key === "reset") restoreAll();
closeMenus();
});
}
root.querySelectorAll('[data-action="togglePanels"]').forEach((btn) => {
btn.addEventListener("mousedown", (e) => e.stopPropagation());
btn.addEventListener("click", (e) => {
e.stopPropagation();
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");
closeMenus();
});
});
const body = root.querySelector(".iwb-editor-optionbar-body");
if (body) {
body.addEventListener("mousedown", (e) => e.stopPropagation());
body.addEventListener("click", (e) => {
const btn = e.target.closest('[data-opt="shape"]');
if (!btn) return;
e.stopPropagation();
S.selectionKind = btn.dataset.value === "ellipse" ? "ellipse" : "rect";
renderOptionBar();
toast("选区形状:" + (S.selectionKind === "ellipse" ? "椭圆" : "矩形"), "info");
});
const onFeather = (e) => {
const input = e.target.closest('[data-opt="feather"]');
if (!input) return;
S.selectionFeather = clamp(parseInt(input.value, 10) || 0, 0, 20);
if (S.selection && S.selection.active) S.selection.feather = S.selectionFeather;
updateStatusbar();
};
body.addEventListener("input", onFeather);
body.addEventListener("change", onFeather);
}
const modal = root.querySelector(".iwb-editor-modal") || root;
modal.addEventListener("mousedown", (e) => {
if (!e.target.closest(".iwb-editor-more-wrap") && !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 bindEvents() {
bindToolButtons();
bindColorPanel();
bindCropConstraintControls();
bindColorPalette();
bindFillToggle();
bindLayerOrderButtons();
bindBrushSizeControls();
bindBrushParams();
bindZoomButtons();
bindHistoryActions();
bindCropActions();
bindLayerAddActions();
bindExportActions();
bindWheelZoom();
bindTextInput();
bindGlobalListeners();
}
function bindToolButtons() {
runtime.el.querySelectorAll(".iwb-editor-tool").forEach((btn) => {
btn.addEventListener("mousedown", (e) => e.stopPropagation());
btn.addEventListener("click", () => setTool(btn.dataset.tool));
});
}
function bindColorPanel() {
const setPanelColor = (color) => applyColorChange(color);
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);
});
runtime.el.querySelectorAll(".iwb-editor-color-panel-swatch").forEach((btn) => btn.addEventListener("click", (e) => {
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", () => 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;
}
setPanelColor(hsvToHex(hueValue, satValue, valValue));
};
if (sv) {
sv.addEventListener("pointerdown", (e) => {
sv.setPointerCapture(e.pointerId);
pick(sv, e);
});
sv.addEventListener("pointermove", (e) => {
if (e.buttons) pick(sv, e);
});
}
if (hue) {
hue.addEventListener("pointerdown", (e) => {
pick(hue, e);
});
hue.addEventListener("pointermove", (e) => {
if (e.buttons) pick(hue, e);
});
}
}
function bindCropConstraintControls() {
runtime.el.querySelectorAll(".iwb-editor-constraint-btn[data-ratio]").forEach((btn) => {
btn.addEventListener("mousedown", (e) => e.stopPropagation());
btn.addEventListener("click", () => {
const r = btn.dataset.ratio;
runtime.el.querySelectorAll(".iwb-editor-constraint-btn[data-ratio]").forEach((b) => b.classList.remove("active"));
btn.classList.add("active");
const ratio = parseRatio(r);
if (ratio > 0) {
setConstraint("ratio", ratio, 0, 0);
} else {
setConstraint("free", 0, 0, 0);
}
});
});
const sizeToggle = runtime.el.querySelector('[data-action="toggleSizeConstraint"]');
if (sizeToggle) sizeToggle.addEventListener("click", () => {
if (S.cropConstraint.type === "size") setConstraint("free", 0, 0, 0);
else {
const w = parseInt(runtime.el.querySelector(".iwb-editor-size-w").value, 10), h = parseInt(runtime.el.querySelector(".iwb-editor-size-h").value, 10);
if (w > 0 && h > 0) setConstraint("size", w / h, w, h);
}
});
bindIf('[data-action="applySize"]', "mousedown", (e) => e.stopPropagation());
bindIf('[data-action="applySize"]', "click", () => {
const w = parseInt(runtime.el.querySelector(".iwb-editor-size-w").value, 10);
const h = parseInt(runtime.el.querySelector(".iwb-editor-size-h").value, 10);
if (w > 0 && h > 0) {
runtime.el.querySelectorAll(".iwb-editor-constraint-btn[data-ratio]").forEach((b) => b.classList.remove("active"));
setConstraint("size", w / h, w, h);
}
});
}
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 bindBrushSizeControls() {
const slider = runtime.el.querySelector(".iwb-editor-brush-size");
const brushNum = runtime.el.querySelector(".iwb-editor-brush-num");
let lwHistoryPushed = false;
const syncBrushSize = (value, continuous) => {
const v = clamp(parseInt(value, 10) || 1, 1, 300);
S.brushSize = v;
slider.value = v;
if (brushNum && document.activeElement !== brushNum) brushNum.value = v;
const sh = getSelectedShape();
if (sh && !sh.locked && sh.lw !== v) {
if (!continuous || !lwHistoryPushed) {
saveSnapshot();
lwHistoryPushed = true;
}
sh.lw = v;
renderObjects();
renderLayerPanel();
}
if (!continuous) lwHistoryPushed = false;
};
runtime.el.querySelectorAll(".iwb-editor-brush-preset").forEach((btn) => {
btn.addEventListener("mousedown", (e) => e.stopPropagation());
btn.addEventListener("click", () => syncBrushSize(btn.dataset.brushSize, false));
});
slider && slider.addEventListener("input", () => syncBrushSize(slider.value, true));
slider && slider.addEventListener("change", () => syncBrushSize(slider.value, false));
if (brushNum) {
brushNum.addEventListener("mousedown", (e) => e.stopPropagation());
brushNum.addEventListener("input", () => {
const v = clamp(parseInt(brushNum.value, 10) || 1, 1, 300);
syncBrushSize(v, true);
});
brushNum.addEventListener("blur", () => {
brushNum.value = S.brushSize;
lwHistoryPushed = false;
});
}
}
function bindBrushParams() {
const hardnessSlider = runtime.el.querySelector(".iwb-editor-brush-hardness");
hardnessSlider && hardnessSlider.addEventListener("input", () => {
S.brushHardness = parseInt(hardnessSlider.value, 10);
runtime.el.querySelector(".iwb-editor-brush-hardness-val").textContent = S.brushHardness;
});
const opacitySlider = runtime.el.querySelector(".iwb-editor-brush-opacity");
opacitySlider && opacitySlider.addEventListener("input", () => {
S.brushOpacity = parseInt(opacitySlider.value, 10) / 100;
runtime.el.querySelector(".iwb-editor-brush-opacity-val").textContent = opacitySlider.value + "%";
if (S.strokeCanvas) S.strokeCanvas.style.opacity = S.brushOpacity;
});
}
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);
});
bindIf('[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 bindCropActions() {
bindIf('[data-action="confirmCrop"]', "click", confirmCrop);
bindIf('[data-action="cancelCrop"]', "click", cancelCrop);
}
function bindLayerAddActions() {
bindIf('[data-action="addBitmapLayer"]', "mousedown", (e) => e.stopPropagation());
bindIf('[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();
});
bindIf('[data-action="addBlankLayer"]', "mousedown", (e) => e.stopPropagation());
bindIf('[data-action="addBlankLayer"]', "click", () => {
addBlankLayer();
});
}
function bindExportActions() {
bindIf('[data-action="cancel"]', "click", close);
bindIf('[data-action="download"]', "click", () => exportResult("download"));
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");
textInput && textInput.addEventListener("mousedown", (e) => e.stopPropagation());
textInput && textInput.addEventListener("keydown", (e) => {
e.stopPropagation();
if (e.key === "Enter") {
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;
});
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(2, S.brushSize), fill: !!S.penPath.closed, opacity: 1, visible: true, locked: false, z: ++S.zCounter };
S.shapeLayers.push(shape);
selectUnit("shape", shape.id);
S.penPath = null;
renderObjects();
renderLayerPanel();
}
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;
if ((S.tool === "brush" || S.tool === "eraser") && !S.isDrawing) clearToolRing();
if (S.tool === "picker") hidePickerTip();
});
S.canvasStack.addEventListener("dblclick", (e) => {
if (S.placingImage) return;
const pos = getPos(e);
if (S.tool === "pen" && S.penPath) {
commitPenPath();
return;
}
if (S.tool === "select" || S.tool === "pen") {
const penShape = getPenEditingShape();
if (penShape) {
const pi = hitPenPoint(pos, penShape, Math.max(14 / S.zoom, 8));
if (pi >= 0) {
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;
}
return;
}
const hitPen = hitShapeLayer(pos, true);
if (hitPen && hitPen.type === "pen") {
e.preventDefault();
beginPenEdit(hitPen);
return;
}
}
if (S.tool !== "text" && S.tool !== "select") return;
const hit = hitTextLayer(pos);
if (hit) {
selectUnit("text", hit.id);
if (hit.locked) return;
renderObjects();
showTextInput(hit.x, hit.y, hit);
}
});
}
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();
}
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;
return t && (t.tagName === "INPUT" || t.tagName === "TEXTAREA");
}
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 === "Enter" && S.tool === "pen" && S.penPath) {
e.preventDefault();
commitPenPath();
return;
}
if (e.key === "Escape") {
if (isTyping(e)) {
hideTextInput();
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();
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;
}
const toolByKey = { "1": "select", "2": "brush", "3": "eraser", "4": "pen", "5": "text", "6": "rect", "7": "circle", "8": "arrow", "9": "picker", "0": "crop" };
const letterTools = { m: "marquee", l: "lasso", v: "select", b: "brush", e: "eraser", t: "text", c: "crop" };
if (!mod && !e.altKey && Object.prototype.hasOwnProperty.call(toolByKey, e.key)) {
e.preventDefault();
setTool(toolByKey[e.key]);
return;
}
if (!mod && !e.altKey && Object.prototype.hasOwnProperty.call(letterTools, key)) {
e.preventDefault();
setTool(letterTools[key]);
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 (e.code === "Space") {
e.preventDefault();
if (!S.spaceDown) {
S.spaceDown = true;
updateCursor();
}
return;
}
if (mod && (e.key === "]" || e.key === "[")) {
e.preventDefault();
const up = e.key === "]";
moveLayer(e.shiftKey ? up ? "top" : "bottom" : up ? "up" : "down");
return;
}
if (mod && key === "z") {
e.preventDefault();
if (e.shiftKey) redo();
else undo();
}
}
function onKeyup(e) {
if (e.key === "Shift") S._shiftDown = false;
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);
try {
window.alert("粘贴失败:" + (err && err.message || "无法读取剪贴板里的图片链接"));
} catch (e) {
}
}
}
// 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));
for (const [c, cx] of [[S.overlayCanvas, S.overlayCtx], [S.selectionCanvas, S.selectionCtx], [S.cursorCanvas, S.cursorCtx]]) {
if (!c || !cx) continue;
c.width = S.imgW + S.overlayPad * 2;
c.height = S.imgH + S.overlayPad * 2;
cx.setTransform(1, 0, 0, 1, S.overlayPad, S.overlayPad);
}
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
});
const drawCanvas = createLayerCanvas();
const drawCtx = drawCanvas.getContext("2d", { willReadFrequently: true });
drawCtx.clearRect(0, 0, S.imgW, S.imgH);
S.layers.push({
id: "draw",
name: "画笔标注",
canvas: drawCanvas,
ctx: drawCtx,
opacity: 1,
visible: true,
locked: false,
transformable: true,
x: 0,
y: 0,
w: S.imgW,
h: S.imgH,
color: S.color,
lineWidth: S.brushSize,
z: 1
});
S.activeLayerId = "draw";
S.zCounter = Math.max(S.layers.length - 1, 0);
S.textCtx.clearRect(0, 0, S.imgW, S.imgH);
S.strokeCtx.clearRect(0, 0, S.imgW, S.imgH);
clearOverlay();
S.pickerComposite = null;
renderObjects();
computeFit();
S.viewX = null;
applyView();
renderLayerPanel();
bindCanvasEvents();
}
function computeFit() {
const availW = Math.max(50, S.canvasWrap.clientWidth - 48);
const availH = Math.max(50, S.canvasWrap.clientHeight - 48);
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() {
S.zoom = 1;
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(S.zoom, 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 = Math.max(13 / Math.max(S.zoom, 1e-4), 9);
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 r = Math.max(8 / Math.max(S.zoom, 1e-4), 6);
ctx.save();
ctx.strokeStyle = "#e8a735";
ctx.lineWidth = 2 / Math.max(S.zoom, 1e-4);
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, Math.PI * 0.15, Math.PI * 1.85);
ctx.stroke();
}
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/objects.js
var TEXT_FONT = (size) => "bold " + size + "px sans-serif";
function textBounds(t) {
const ctx = S.textCtx;
ctx.font = TEXT_FONT(t.fontSize);
const w = ctx.measureText(t.text).width;
const h = t.fontSize * 1.25;
return { x: t.x, y: t.y, w, h };
}
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 / S.zoom;
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 / S.zoom, s.lw)) return true;
if (s.closed && pts.length > 2 && distToSeg(pos.x, pos.y, pts[pts.length - 1].x, pts[pts.length - 1].y, pts[0].x, pts[0].y) <= Math.max(8 / S.zoom, s.lw)) return true;
if (!includeInterior) return false;
const b = shapeBounds(s);
return pos.x >= b.x && pos.x <= b.x + b.w && pos.y >= b.y && pos.y <= b.y + b.h;
}
if (s.type === "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 / S.zoom, 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 / S.zoom, 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.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;
}
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 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 || 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 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 / S.zoom;
const R = Math.max(18 / S.zoom, 11);
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 / S.zoom;
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 / S.zoom, S.brushSize * 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(2, S.brushSize) / S.zoom;
ctx.setLineDash([8 / S.zoom, 5 / S.zoom]);
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, Math.max(4, 6 / S.zoom), 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 / S.zoom;
octx.setLineDash([6 / S.zoom, 3 / S.zoom]);
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 = 8.5 / S.zoom;
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();
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 / S.zoom;
octx.setLineDash([6 / S.zoom, 3 / S.zoom]);
const corners = boxCorners(b.x - 2 / S.zoom, b.y - 2 / S.zoom, b.w + 4 / S.zoom, b.h + 4 / S.zoom, rot);
octx.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 = 7 / S.zoom;
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 = Math.max(12 / S.zoom, 6);
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 = Math.max(7 / S.zoom, 5);
ctx.save();
ctx.lineWidth = 1.5 / S.zoom;
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, Math.max(3 / S.zoom, 2), 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 rect = S.canvasStack.getBoundingClientRect();
const wrapRect = S.canvasWrap.getBoundingClientRect();
const sx = rect.width / S.imgW;
const sy = rect.height / S.imgH;
input.style.left = rect.left - wrapRect.left + x * sx + "px";
input.style.top = rect.top - wrapRect.top + y * sy + "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;
}
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(16, S.brushSize * 6),
opacity: 1,
visible: true,
locked: false,
z: ++S.zCounter
};
S.textLayers.push(layer);
selectUnit("text", layer.id);
renderObjects();
committed = true;
}
hideTextInput();
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/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 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);
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;
const pad = S.overlayPad || 0;
ctx.save();
ctx.setTransform(1, 0, 0, 1, 0, 0);
ctx.clearRect(0, 0, S.imgW + pad * 2, S.imgH + pad * 2);
ctx.restore();
ctx.setTransform(1, 0, 0, 1, pad, pad);
}
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.obj.opacity == null ? 1 : u.obj.opacity;
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() {
S.tool = S.prevTool && S.prevTool !== "picker" ? S.prevTool : "brush";
S.prevTool = null;
S.pickerComposite = null;
hidePickerTip();
updateToolUI();
updateBrushParamUI();
if (S.tool === "crop") {
showCropBar();
updateCropInfo();
} else {
cancelCrop();
hideCropBar();
}
renderObjects();
}
function applyColorChange(color) {
S.color = color;
updateColorUI();
const t = getSelectedText();
if (t && !t.locked && t.color !== S.color) {
saveSnapshot();
t.color = S.color;
renderObjects();
}
const sh = getSelectedShape();
if (sh && !sh.locked && S.tool !== "text" && sh.color !== S.color) {
saveSnapshot();
sh.color = S.color;
renderObjects();
}
}
function setTool(tool) {
if (S.placingImage) cancelImagePlacement();
commitTextInput();
if (tool !== "select" && tool !== "pen") {
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;
if (tool !== "select") S.selectedLayerId = null;
if (tool !== "text" && tool !== "select") S.selectedTextId = null;
if (tool !== "rect" && tool !== "circle" && tool !== "arrow" && tool !== "pen" && tool !== "select") S.selectedShapeId = null;
S.bitmapDrag = null;
S.textDrag = null;
S.shapeDrag = null;
S.pickerComposite = null;
hidePickerTip();
updateToolUI();
updateBrushParamUI();
if (tool === "crop") {
showCropBar();
updateCropInfo();
} else {
cancelCrop();
hideCropBar();
}
renderObjects();
renderLayerPanel();
if (S.renderAll) S.renderAll();
}
// 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;
const pad = S.overlayPad || 0;
ctx.save();
ctx.setTransform(1, 0, 0, 1, 0, 0);
ctx.clearRect(0, 0, S.imgW + pad * 2, S.imgH + pad * 2);
ctx.restore();
ctx.setTransform(1, 0, 0, 1, pad, pad);
}
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 / S.zoom;
ctx.setLineDash([8 / S.zoom, 4 / S.zoom]);
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 / S.zoom;
ctx.save();
ctx.fillStyle = "#ffffff";
ctx.strokeStyle = "#4488ff";
ctx.lineWidth = 1.5 / S.zoom;
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 / S.zoom;
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;
}
disposeSelection();
const tmp = getCompositeCanvas();
const sx = Math.round(x), sy = Math.round(y);
const sw = Math.round(w), sh = Math.round(h);
const cropC = document.createElement("canvas");
const c = S.cropConstraint;
const srcX = Math.max(0, sx);
const srcY = Math.max(0, sy);
const srcRight = Math.min(S.imgW, sx + sw);
const srcBottom = Math.min(S.imgH, sy + sh);
const srcW = Math.max(0, srcRight - srcX);
const srcH = Math.max(0, srcBottom - srcY);
const dstX = srcX - sx;
const dstY = srcY - sy;
if (c.type === "size" && c.sizeW > 0 && c.sizeH > 0) {
cropC.width = c.sizeW;
cropC.height = c.sizeH;
const cctx = cropC.getContext("2d");
const scaleX2 = c.sizeW / sw;
const scaleY2 = c.sizeH / sh;
if (srcW > 0 && srcH > 0) {
cctx.drawImage(
tmp,
srcX,
srcY,
srcW,
srcH,
dstX * scaleX2,
dstY * scaleY2,
srcW * scaleX2,
srcH * scaleY2
);
}
S.imgW = c.sizeW;
S.imgH = c.sizeH;
} else {
cropC.width = sw;
cropC.height = sh;
const cctx = cropC.getContext("2d");
if (srcW > 0 && srcH > 0) {
cctx.drawImage(tmp, srcX, srcY, srcW, srcH, dstX, dstY, srcW, srcH);
}
S.imgW = sw;
S.imgH = sh;
}
const isSize = c.type === "size" && c.sizeW > 0 && c.sizeH > 0;
const scaleX = isSize ? c.sizeW / sw : 1;
const scaleY = isSize ? c.sizeH / sh : 1;
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;
setupCanvas(cropC);
S.history = [];
S.redoStack = [];
S.cropRect = null;
S.cropMoving = false;
S.moveStart = null;
clearOverlay();
updateCropInfo();
if (S.renderAll) S.renderAll();
}
function cancelCrop() {
S.cropRect = null;
S.cropHandle = null;
S.cropMoving = false;
S.moveStart = null;
clearOverlay();
updateCropInfo();
}
function showCropBar() {
runtime.el.querySelector(".iwb-editor-crop-bar").style.display = "flex";
}
function hideCropBar() {
runtime.el.querySelector(".iwb-editor-crop-bar").style.display = "none";
}
// 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) {
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;
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();
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;
}
const drawCanvas = createLayerCanvas();
const drawCtx = drawCanvas.getContext("2d", { willReadFrequently: true });
const draw = {
id: "draw",
name: "画笔标注",
canvas: drawCanvas,
ctx: drawCtx,
opacity: 1,
visible: true,
locked: false,
transformable: true,
x: 0,
y: 0,
w: S.imgW,
h: S.imgH,
rotation: 0,
color: S.color,
lineWidth: S.brushSize,
z: 1
};
S.layers = base ? [base, draw] : [draw];
S.activeLayerId = "draw";
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.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 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;
};
S.exportOptions = {
preset: get("preset", DEFAULT_EXPORT.preset) === "ecom800" ? "ecom800" : "original",
format: ["png", "jpeg", "webp"].indexOf(get("format", DEFAULT_EXPORT.format)) >= 0 ? get("format", DEFAULT_EXPORT.format) : "png",
bg: get("bg", DEFAULT_EXPORT.bg) === "white" ? "white" : "transparent",
maxKB: Math.max(0, Number(get("maxKB", 0)) || 0),
size: Math.max(64, Number(get("size", 800)) || 800)
};
if (S.exportOptions.preset === "ecom800" && !S.exportOptions.maxKB) S.exportOptions.maxKB = 500;
renderExportUI();
}
function setExportOption(key, value) {
if (!S.exportOptions) loadExportOptions();
S.exportOptions[key] = value;
if (key === "preset" && value === "ecom800") S.exportOptions.maxKB = 500;
if (key === "preset" && value === "original") S.exportOptions.maxKB = 0;
const st = settings();
if (st && typeof st.set === "function") {
try {
st.set(SETTINGS_KEY[key], value);
} catch (e) {
}
}
renderExportUI();
}
function renderExportUI() {
const o = S.exportOptions || DEFAULT_EXPORT;
const root = runtime.el;
if (!root) return;
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));
});
const summary = root.querySelector(".iwb-editor-export-summary");
if (summary) summary.textContent = o.preset === "ecom800" ? o.size + "×" + o.size + " · " + o.format.toUpperCase() + (o.maxKB ? " · ≤" + o.maxKB + "KB" : "") : "原尺寸 " + S.imgW + "×" + S.imgH + " · " + o.format.toUpperCase();
}
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 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 (o.bg === "white" || o.format === "jpeg") {
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 (o.bg === "white" || o.format === "jpeg") {
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.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 info = { bytes: blob.size, width: canvas.width, height: canvas.height, format: S.exportOptions.format, preset: S.exportOptions.preset };
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");
}
// 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;
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();
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.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.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) {
const pad = S.overlayPad || 0;
S.cursorCtx.setTransform(1, 0, 0, 1, 0, 0);
S.cursorCtx.clearRect(0, 0, S.imgW + pad * 2, S.imgH + pad * 2);
S.cursorCtx.setTransform(1, 0, 0, 1, pad, pad);
}
}
function renderAll() {
if (!S.open || !runtime.el) return;
renderObjects();
renderLayerPanel();
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.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);
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 || "图片跨域"));
}
}
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,
doc: { w: S.imgW, h: S.imgH },
layers: S.layers.map((l) => ({ id: l.id, name: l.name, z: l.z, locked: !!l.locked, visible: l.visible !== false })),
shapes: S.shapeLayers.map((s) => ({ id: s.id, type: s.type })),
texts: S.textLayers.map((t) => ({ id: t.id, text: t.text })),
selectedShapeId: S.selectedShapeId,
selectedTextId: S.selectedTextId,
activeLayerId: S.activeLayerId,
selection: selectionInfo(),
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,
interaction: S.interaction,
ants: !!S._antFrame,
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;
}
}
});
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 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 background: rgba(255, 255, 255, 0.95);\n color: #1e1e2e;\n z-index: 10;\n min-width: 120px;\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\n/* 图层项 */\n.iwb-layer-item {\n display: flex;\n align-items: center;\n gap: 6px;\n padding: 6px 8px;\n border-radius: 6px;\n cursor: pointer;\n transition: background 0.12s;\n margin-bottom: 2px;\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.iwb-layer-item[draggable="true"] { cursor: grab; }\n.iwb-layer-item.dragging { opacity: 0.45; }\n.iwb-layer-item.drop-target { outline: 1px dashed #e8a735; background: rgba(232, 167, 53, 0.16); }\n/* 画笔/橡皮作用目标:与「选中」分离,避免出现两个图层同时高亮 */\n.iwb-layer-paint { flex: 0 0 auto; color: #a6adc8; font-size: 11px; opacity: 0.85; }\n.iwb-layer-color { width: 22px; height: 22px; padding: 0; border: 1px solid #45475a; border-radius: 50%; background: transparent; cursor: pointer; flex: 0 0 auto; }\n.iwb-layer-width { width: 42px; height: 22px; padding: 2px 3px; border: 1px solid #45475a; border-radius: 4px; background: #1e1e2e; color: #e8a735; font-size: 11px; text-align: center; flex: 0 0 auto; }\n.iwb-layer-width:focus { outline: none; border-color: #e8a735; }\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.iwb-layer-color, .iwb-layer-width { display: none !important; }\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.iwb-layer-color, .iwb-layer-width { 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.iwb-layer-color, .iwb-layer-width { 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.iwb-editor-header > .iwb-editor-export-actions { order: 1; margin-left: 0; margin-right: 4px; }\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.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.iwb-opt-hint { color: #7f849c; font-size: 11px; margin-left: auto; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }\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/* ---- 竖工具栏:真正固定在左侧,给 main 留出 56px ---- */\n.iwb-editor-header > .iwb-editor-tools {\n position: fixed !important; left: 8px !important; top: 112px !important;\n width: 40px !important; max-height: calc(100vh - 128px);\n flex-direction: column; padding: 5px !important; border-radius: 10px;\n overflow-y: auto; overflow-x: hidden; scrollbar-width: none; z-index: 50;\n}\n.iwb-editor-header > .iwb-editor-tools::-webkit-scrollbar { display: none; }\n.iwb-editor-header > .iwb-editor-tools .iwb-editor-tool,\n.iwb-editor-header > .iwb-editor-tools .iwb-editor-action { width: 30px !important; height: 30px !important; min-width: 30px; flex: 0 0 auto; }\n.iwb-editor-header > .iwb-editor-tools .iwb-editor-divider { width: 22px; height: 1px; margin: 3px 0; flex: 0 0 auto; }\n.iwb-editor-header > .iwb-editor-tools .iwb-editor-fill-btn { width: 30px !important; padding: 3px 0 !important; font-size: 10px; writing-mode: vertical-rl; }\n.iwb-editor-main { padding-left: 56px; }\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-export-actions .iwb-editor-btn-cancel { display: none; }\n}\n\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)