feat(plugin): 新增 image-annotate 标注/修图插件 + 构建链

- 编辑器逐字移植自 iwb-plaus/iwb-cutout-extension(11 模块 + 2 个 shared 文件,纯 Canvas 2D、零第三方库)
- plugin/ 存 ESM 源码,src/index.js 是构建产物(提交进仓,CI 只校验不构建)
- scripts/build-plugin.mjs:esbuild 打包 + banner/footer 手写单引号 manifest + 产物自检
- 能力 commands / nodeActions / canvas / canvasWrite;入口 = 节点漂浮菜单 + 右键命令
- 导出模式按编辑器字面量映射:replace → setNodeImage,newNode → createImageNode
This commit is contained in:
qiqi committed 2026-10-19 14:03:55 +08:00
1 parent 2b93a6bfeb
commit e7b6e23f8f
24 files changed
+11540 -1

No files matched your search

+48
View File
@@ -0,0 +1,48 @@
# 标注 / 修图(插件)
在宿主里选中一个带图的节点,打开**全屏标注编辑器**(画笔 / 矩形 / 箭头 / 文字 / 橡皮 / 吸管 / 抓手 / 裁剪,
图层、撤销重做、缩放平移),导出后**覆盖原节点**或**新建一个节点**。
编辑器**移植自** `iwb-plaus` 仓库的 `iwb-cutout-extension`(纯 Canvas 2D、零第三方库):
- 源:`/Users/qiqi/open/github/iwb-plaus/iwb-cutout-extension/src/editor/`(11 个模块)+ `src/shared/{image-math,layer-logic}.js`
- 差异:只有「宿主胶水」(`plugin/glue.js`、`plugin/entry.js`)是新写的;编辑器模块与样式**逐字移植**,便于日后回灌上游。
- 原扩展的 CSS 由 `manifest.json` 的 `content_scripts.css` 注入;插件没有 manifest,改为构建时以字符串内联、运行时注入 `<style>`。
## 入口
- **节点漂浮菜单**「标注 / 修图」(`ref` / `out` / `gen` / `layer` 节点)
- 右键菜单「插件命令 → 标注 / 修图:选中节点」
导出后由编辑器自己 `close()`:
- 点「覆盖」→ `ctx.canvas.setNodeImage(nodeId, dataUrl)`
- 点「新建」→ `ctx.canvas.createImageNode({ dataUrl, name })`(宿主会建一个 `ref` 节点)
## 已知限制(v1)
- **远程 http(s) 图片不支持**:`ctx.canvas.getNodeImage` 对非 data: 字符串只返回 `{ url }`(画布读像素会污染),
插件会给出「请先转存为本地位图」的提示。对象引用(`{__blob}` 等)会被宿主解成 dataUrl,正常可用。
- 4K 图导出走 Blob → 再转 dataURL 回写(约 44MB base64 一次),内存开销已在编辑器侧尽量压到最低。
## 开发 / 构建
源码在 `plugin/`,产物是 `src/index.js`(**提交进仓**,CI 只校验不构建)。
```bash
cd /Users/qiqi/open/github/iwb-plugins
npm install # 只为 esbuild(devDependency)
npm run build -- image-annotate # plugin/entry.js → src/index.js(含产物自检)
npm run validate # 契约校验
```
**构建为什么要分三段**(`scripts/build-plugin.mjs`):
1. esbuild 会把字符串统一改写成双引号,而 `scripts/validate.mjs` 只认单引号 manifest;
2. 校验器取「文件里第一个 id 字面量」判定插件 id,manifest 必须排在 bundle 之前。
→ `plugin/manifest.banner.js`(单引号 manifest,原样放最前)+ esbuild bundle + `plugin/manifest.footer.js`(注册调用)。
`version` 只有一处真源:构建时用 `package.json` 的 `version` 替换 banner 里的 `__PLUGIN_VERSION__`。
> 注意:banner 的**注释**里也不能出现 id + 冒号 + 单引号的组合,否则会被校验器当成 manifest 抢走(踩过一次)。
## 发布
```bash
cd /Users/qiqi/open/github/image-workbench-web
cp /Users/qiqi/open/github/iwb-plugins/image-annotate/src/index.js /tmp/plugin-image-annotate.js
node scripts/plugins-publish.mjs /tmp/plugin-image-annotate.js --upload --version image-annotate=1.0.0
```
发布后刷新即生效(KV 为测试站/正式站共享;新插件在插件管理里**默认未启用**,需手动开启)。
+11
View File
@@ -0,0 +1,11 @@
{
"name": "@iwb-plugin/image-annotate",
"private": true,
"version": "1.0.0",
"description": "IWB 插件:图片标注 / 修图(编辑器移植自 iwb-plaus 扩展,纯 Canvas 2D)",
"ibwPlugin": {
"id": "image-annotate",
"entry": "src/index.js",
"apiVersion": 1
}
}
+1338
View File
File diff suppressed because it is too large. Load diff
+326
View File
@@ -0,0 +1,326 @@
/* crop.js - 裁剪工具
* 节:裁剪、裁剪栏。
* 遮罩绘制写 S.overlayCanvas,确认裁剪后重绘位图图层。
*/
'use strict'
import { S, runtime } from './state.js'
import { getCompositeCanvas } from './tools.js'
import { setupCanvas } from './viewport.js'
// ============ 裁剪 ============
// parseRatio 由 shared/image-math.js 提供(可单测)
/** 设置裁剪约束 */
export 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 }
}
}
export 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 }
}
export 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 = '--'
}
}
export function clearOverlay() {
const ctx = S.overlayCtx
const pad = S.overlayPad || 0
ctx.save()
ctx.setTransform(1, 0, 0, 1, 0, 0)
ctx.clearRect(0, 0, S.imgW + pad * 2, S.imgH + pad * 2)
ctx.restore()
ctx.setTransform(1, 0, 0, 1, pad, pad)
}
export function drawCropPreview(x1, y1, x2, y2) {
const ctx = S.overlayCtx
clearOverlay()
let rx, ry, rw, rh
if (x2 !== undefined) {
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()
}
export 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
}
export function hitCropHandle(pos) {
if (!S.cropRect) return null
const pts = cropHandlePoints(S.cropRect.x, S.cropRect.y, S.cropRect.w, S.cropRect.h)
const R = 12 / S.zoom
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
}
export 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 }
}
export function confirmCrop() {
if (!S.cropRect) return
const { x, y, w, h } = S.cropRect
if (w < 2 || h < 2) { cancelCrop(); return }
// 合成所有可见图层
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) {
// 尺寸约束:先画到 sw×sh 画布再缩放到目标尺寸
cropC.width = c.sizeW
cropC.height = c.sizeH
const cctx = cropC.getContext('2d')
const scaleX = c.sizeW / sw
const scaleY = c.sizeH / sh
if (srcW > 0 && srcH > 0) {
cctx.drawImage(tmp, srcX, srcY, srcW, srcH,
dstX * scaleX, dstY * scaleY, srcW * scaleX, srcH * scaleY)
}
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.zoom = 1
setupCanvas(cropC)
S.history = []
S.redoStack = []
S.cropRect = null
S.cropMoving = false
S.moveStart = null
clearOverlay()
updateCropInfo()
}
export function cancelCrop() {
S.cropRect = null
S.cropHandle = null
S.cropMoving = false
S.moveStart = null
clearOverlay()
updateCropInfo()
}
// ============ 裁剪栏 ============
export function showCropBar() { runtime.el.querySelector('.iwb-editor-crop-bar').style.display = 'flex' }
export function hideCropBar() { runtime.el.querySelector('.iwb-editor-crop-bar').style.display = 'none' }
+208
View File
@@ -0,0 +1,208 @@
/* dom.js - 编辑器 DOM 构建与图片加载
* 节:DOM 创建、图片加载。
* createEl 负责创建遮罩根节点并写入 runtime.el,随后把各 canvas/面板
* 引用挂到 S 上;open() 依赖它保证 el 只创建一次。
*/
'use strict'
import { S, runtime } from './state.js'
import { bindEvents } from './events.js'
// ============ DOM 创建 ============
export 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">图片编辑</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" data-action="reset" 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="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>
<button class="iwb-editor-action iwb-editor-action-restore" data-action="restore" 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" ry="2"/><circle cx="8.5" cy="8.5" r="1.5"/><polyline points="21 15 16 10 5 21"/></svg></button>
</div>
<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 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">
<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-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="导入图片为新图层"><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>
</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>
<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>
<div class="iwb-editor-footer">
</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.textCtx = S.textCanvas.getContext('2d')
S.strokeCtx = S.strokeCanvas.getContext('2d')
S.overlayCtx = S.overlayCanvas.getContext('2d')
bindEvents()
}
// ============ 图片加载 ============
/**
* dataURL 一律先转 blob URL 再喂给 Image:img.src 直接挂 dataURL 会让
* 元素在整个编辑会话期间持有一份几十 MB 的字符串(4K 源图 ≈44MB),而
* 解码只需一次 —— 载入完成立即 revoke,img 保留的是自己的解码资源,
* 之后 drawImage/复原都不再依赖那串字符。
*/
export async function loadImage(src) {
let useSrc = src
let revokeUrl = null
if (typeof src === 'string' && src.slice(0, 5) === 'data:') {
try {
const blob = await (await fetch(src)).blob()
useSrc = URL.createObjectURL(blob)
revokeUrl = useSrc
} catch (e) { useSrc = src } // fetch 不可用/失败:回落原 dataURL
}
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) { /* ignore */ } }
}
}
File diff suppressed because it is too large. Load diff
+224
View File
@@ -0,0 +1,224 @@
/* history.js - 历史快照与撤销/重做
* 节:历史快照(所有位图图层 + 矢量对象)。
* 约定:快照序列化依赖 shared/layer-logic.js 的 restorePath/needsPixelSnapshot,
* 与 layers.js 各自独立实现「恢复图层」路径,互不 import。
* 暴露 snapshotStats、HISTORY_MAX_ENTRIES、HISTORY_MAX_BYTES 供 __stats 观测。
*/
'use strict'
import { S } from './state.js'
import { clearOverlay, updateCropInfo } from './crop.js'
import { hideTextInput, renderObjects } from './objects.js'
import { purgeVectorCanvases, redrawBitmapLayer, renderLayerPanel, reorderLayerCanvas } from './layers.js'
import { setupCanvas } from './viewport.js'
import { updateAllUI } from './events.js'
import { isDrawableLayer, needsPixelSnapshot, restorePath } from '../vendor/layer-logic.js'
// ============ 历史快照(所有位图图层 + 矢量对象) ============
// 快照开销统计:控制台 window.__iwbEditor.__stats() 可读
export const snapshotStats = { snapshots: 0, getImageDataCalls: 0, bytesWritten: 0 }
// restorePath()(快照端"要不要拍"与恢复端"要不要读"的共同判定)
// 由 shared/layer-logic.js 提供,并有单元测试守护两边一致这条不变量。
/**
* 捕获当前状态
* @param {{metaOnly?: boolean}} [opts]
* metaOnly=true:只取几何/矢量/图层元数据。拖拽结束时仅用于"有没有变化"的比对,
* 比对从不读像素,此前却照样做全量 getImageData —— 纯浪费。
* 默认:只为 needsPixelSnapshot() 为 true 的图层拍像素,可重绘图层只存几何。
*/
export 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) { /* ignore */ }
if (data) {
snapshotStats.getImageDataCalls++
snapshotStats.bytesWritten += data.data.byteLength
}
}
return {
id: layer.id,
data,
x: layer.x, y: layer.y, w: layer.w, h: layer.h,
rotation: layer.rotation || 0,
transformable: !!layer.transformable,
locked: !!layer.locked
}
})
snapshotStats.snapshots++
return {
bitmaps,
texts: JSON.parse(JSON.stringify(S.textLayers)),
shapes: JSON.parse(JSON.stringify(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 }))
}
}
// 历史既限条数也限字节:大图下"固定 50 条全量像素"峰值可超过 1GB
export const HISTORY_MAX_ENTRIES = 50
/** 字节预算上限/下限:预算随图幅自适应,见 historyBudgetBytes() */
export const HISTORY_MAX_BYTES = 128 * 1024 * 1024
const HISTORY_MIN_BYTES = 32 * 1024 * 1024
/**
* 快照字节预算(按图幅自适应):约「4 条全幅快照」,下限 32MB、上限 128MB。
* 固定 128MB 的问题:1024 预览图每条仅 4MB ⇒ 可囤 32 条(纯浪费);
* 而 4K 图每条 33MB ⇒ 天然只能放 3 条,与上限无关。按图幅算让
* 小图少囤、大图保持现有撤销深度。
*/
export 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
}
/** 压入栈并执行"条数 + 字节"双预算,超出丢最旧 */
export function pushHistory(stack, state) {
state.__bytes = stateBytes(state)
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
}
/** 操作前调用:压入历史,清空重做栈 */
export function saveSnapshot() {
pushHistory(S.history, snapshotState())
S.redoStack = []
}
/** 恢复到指定状态 */
function restoreState(state) {
purgeVectorCanvases()
for (const l of S.layers) l._bounds = undefined
if (state.bitmaps) {
for (let i = 0; i < state.bitmaps.length; i++) {
const bm = state.bitmaps[i]
const layer = S.layers.find(l => l.id === bm.id)
if (layer) {
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 = undefined
}
// 快照端用 restorePath() 决定是否拍像素,这里用同一判定决定是否读像素
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) { /* ignore */ }
}
}
}
}
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; layer.locked = !!meta.locked }
}
reorderLayerCanvas()
}
S.textLayers = state.texts ? JSON.parse(JSON.stringify(state.texts)) : []
S.shapeLayers = state.shapes ? JSON.parse(JSON.stringify(state.shapes)) : []
S.selectedTextId = null
S.textDrag = null
S.selectedShapeId = null
S.shapeDrag = null
renderObjects()
renderLayerPanel()
}
export function undo() {
if (S.placingImage) return
// bitmapDrag 与 textDrag/shapeDrag 对称:位图层拖拽进行中不允许撤销
if (S.isDrawing || S.textDrag || S.shapeDrag || S.bitmapDrag) return
if (S.history.length === 0) return
pushHistory(S.redoStack, snapshotState())
restoreState(S.history.pop())
}
export function redo() {
if (S.placingImage) return
if (S.isDrawing || S.textDrag || S.shapeDrag || S.bitmapDrag) return
if (S.redoStack.length === 0) return
pushHistory(S.history, snapshotState())
restoreState(S.redoStack.pop())
}
export function resetDraw() {
purgeVectorCanvases()
// 清空所有位图图层(保留原图层的内容不变,只清画笔层和后续图层)
for (const layer of S.layers) {
if (layer.id !== 'base') {
layer.ctx.clearRect(0, 0, S.imgW, S.imgH)
if (layer.sourceCanvas) layer.sourceCanvas.getContext('2d').clearRect(0, 0, layer.sourceCanvas.width, layer.sourceCanvas.height)
}
}
S.history = []
S.redoStack = []
S.cropRect = null
S.cropHandle = null
S.cropMoving = false
S.moveStart = null
S.textLayers = []
S.selectedTextId = null
S.textDrag = null
S.textEditingId = null
S.shapeLayers = []
S.selectedShapeId = null
S.shapeDrag = null
renderObjects()
renderLayerPanel()
clearOverlay()
updateCropInfo()
hideTextInput()
}
/** 复原:一键回到打开编辑器时的原始图片(撤销所有标注与裁剪) */
export function restoreOriginal() {
if (!S.originalImage) return
if (!window.confirm('复原将丢弃所有标注和裁剪,回到原始图片。确定继续吗?')) return
S.imgW = S.originalImage.naturalWidth || S.originalImage.width
S.imgH = S.originalImage.naturalHeight || S.originalImage.height
S.zoom = 1
setupCanvas(S.originalImage)
resetDraw()
updateAllUI()
}
+231
View File
@@ -0,0 +1,231 @@
/* IWB 图片编辑器 - 图层化裁剪与标注
* 独立模块,通过 window.__iwbEditor.open() 调用
* 接收 imageBase64,返回编辑后的 dataURL
*
* v2.0.0 特性:
* - 图层系统:位图图层动态管理(原图、画笔、导入图片),可调透明度、显隐、排序
* - 矢量对象(文字/形状)在图层面板中统一展示,z 序可调
* - 统一橡皮:一个橡皮擦除当前活跃位图图层,与画笔共用大小/透明度/软硬
* - 添加位图图层:支持导入新图片作为独立图层
* - 工具:选择 / 画笔 / 矩形 / 箭头 / 文字 / 橡皮 / 吸管 / 抓手 / 裁剪
*
* 分层架构:
* - bitmap layers: 每个位图图层一个 canvas(动态创建/排序),CSS opacity 控制透明度
* - textCanvas: 矢量对象层(文字+形状),共享一个 canvas
* - strokeCanvas: 笔划预览层(一笔结束后合成进活跃图层)
* - overlayCanvas: 选中框/裁剪遮罩/笔刷预览
*/
/* index.js - 模块组装与对外接口
* 汇总各子模块,承载「打开编辑器 / 关闭 / 复原 / 输出」生命周期,
* 并把 window.__iwbEditor = { open, close, __stats } 挂到全局(对外唯一接口)。
* 注意:entries/content.js 必须先 import 本文件再 import content.js。
* 顶层只允许声明与这次 window 赋值,不调用其它模块的函数(避免循环 TDZ)。
*/
'use strict'
import { S, runtime } from './state.js'
import { HISTORY_MAX_BYTES, HISTORY_MAX_ENTRIES, historyBudgetBytes, snapshotStats } from './history.js'
import { cancelImagePlacement } from './placement.js'
import { clearSelection, purgeVectorCanvases } from './layers.js'
import { createEl, loadImage } from './dom.js'
import { getCompositeCanvas } from './tools.js'
import { hideTextInput } from './objects.js'
import { setupCanvas } from './viewport.js'
import { updateAllUI } from './events.js'
// ============ 打开编辑器 ============
export async function open(options) {
if (!options || !options.imageBase64) return
createEl()
S.callbacks = options
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()
} catch (e) {
console.error('[IWB编辑器] 打开失败:', e)
if (runtime.el) runtime.el.style.display = 'none'
if (options.onError) options.onError(e.message)
} finally {
// 源图字符串只在解码这一刻有用(loadImage 内已转 blob URL)。
// 不丢的话 S.callbacks 会在整个编辑会话持有整份 dataURL(4K ≈44MB),
// 打开失败路径更是会一直挂到下次打开才被覆盖。
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.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 = '启用尺寸' }
}
export function close() {
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()
}
/**
* 关闭即释放(对齐宿主「内存里不放大图」的模型):
* 此前 close() 只把遮罩 display:none,历史快照(≤128MB 的全幅 ImageData)、
* 各全幅图层/overlay canvas 的像素缓冲、原图 Image 与 base64 全部继续驻留 ——
* 编辑一张 4K 图后即使退出,堆里仍挂着 ~100MB,直到下次打开编辑器才被重建顶掉。
* 释放后下次 open() 由 setupCanvas + resetState 全量重建,无状态残留依赖。
*/
function releaseEditorMemory() {
// 1) 撤销/重做栈:像素快照是最大头
S.history = []
S.redoStack = []
// 2) 原图引用与吸管合成缓存(各为一张全幅位图)
S.originalImage = null
S.pickerComposite = null
// 3) 交互态复位:关闭后 window mouseup 等全局监听仍活着,靠标志位保证不落到绘制路径
S.isDrawing = false
S.panning = false
S.penDragPt = -1
S.penDragPending = null
S.placingImage = null
S.placingHandle = null
S.placingStart = null
// 4) 位图图层(含 sourceCanvas):置 0 释放像素缓冲并从 DOM 摘除;
// setupCanvas 依赖 S.layers 做清理,这里必须同步清空,避免下次打开残留旧 canvas
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 = []
// 5) 工作 canvas:text / stroke / overlay(overlay 含 18% 交互边距,4K 图约 74MB)
for (const c of [S.textCanvas, S.strokeCanvas, S.overlayCanvas]) {
try { if (c) { c.width = 0; c.height = 0 } } catch (e) { /* ignore */ }
}
// 6) 矢量对象的画布缓存
purgeVectorCanvases()
}
// ============ 输出 ============
/**
* 导出:合成 → PNG 字节 → onResult(out, mode) → close()。
* 用 toBlob 而非 toDataURL —— 编码结果落在浏览器 Blob 存储(堆外),
* 省掉全幅 base64 字符串(4K 图约 44MB JS 堆驻留);onResult 收到 Blob 或 dataURL 均可。
*/
export function exportResult(mode) {
if (S.placingImage) cancelImagePlacement()
const tmp = getCompositeCanvas()
let done = false
const finish = (out) => {
if (done) return
done = true
tmp.width = 0 // 合成画布用完即弃(33MB@4K)
tmp.height = 0
if (S.callbacks && S.callbacks.onResult) {
S.callbacks.onResult(out, mode)
}
close()
}
const fail = (e) => {
if (done) return
done = true
tmp.width = 0
tmp.height = 0
console.error('[IWB编辑器] 导出失败:', e)
if (S.callbacks && S.callbacks.onError) S.callbacks.onError('图片跨域无法导出')
}
try {
if (typeof tmp.toBlob === 'function') {
tmp.toBlob((blob) => {
if (blob) { finish(blob); return }
// toBlob 对非 origin-clean 画布返回 null → 退回 toDataURL 让它抛出明确的 SecurityError
try { finish(tmp.toDataURL('image/png')) } catch (e) { fail(e) }
}, 'image/png')
return
}
finish(tmp.toDataURL('image/png'))
} catch (e) {
fail(e)
}
}
// ============ 暴露接口 ============
/**
* 快照/历史开销观测口(性能回归与手测用):
* history / redo 当前栈深度与占用字节
* snapshots 快照次数
* getImageDataCalls 累计全幅像素读取次数(优化前后最直观的对比指标)
* bytesWritten 累计拍摄的像素字节数
*/
export const __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
})
window.__iwbEditor = {
open,
close,
__stats
}
+721
View File
@@ -0,0 +1,721 @@
/* layers.js - 位图图层管理、矢量对象画布与图层面板
* 节:图层管理、矢量对象独立画布(位图/矢量统一排序)、图层面板 UI,
* 外加原属「图片放置」节末尾的 deleteLayer。
* 约定:位图图层一个 canvas,矢量对象(文字/形状)各自独立 canvas,
* reorderLayerCanvas 按 z 统一排序插入 S.canvasStack。
*/
'use strict'
import { S, runtime } from './state.js'
import { TEXT_FONT, allObjects, deleteSelectedShape, deleteSelectedText, renderObjects, sortLayersByZ, textBounds } from './objects.js'
import { boxCorners, clamp, drawRotationHandles, hitRotationHandle, rotPt, unrotPt } from './viewport.js'
import { drawShape } from './tools.js'
import { saveSnapshot, snapshotState } from './history.js'
import { startImagePlacement } from './placement.js'
import { updateBrushParamUI, updateColorUI } from './events.js'
import { isDrawableLayer } from '../vendor/layer-logic.js'
// ============ 图层管理 ============
/** 创建位图图层 canvas 元素并插入 DOM 栈 */
export 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'
// 插入到 strokeCanvas 之前(位图图层在矢量层之下)
S.canvasStack.insertBefore(c, S.strokeCanvas)
return c
}
/** 按图层 z 序重排 DOM 中的 canvas 元素。
* 所有 canvas 必须共享 canvas-stack 的坐标系;隐藏图层只用 CSS 隐藏,
* 不从 DOM 移除,避免 canvas-stack 在 flex/inline 布局下重新计算位置。 */
export function reorderLayerCanvas() {
const units = []
for (const l of S.layers) units.push({ z: l.z, el: l.canvas, vis: l.visible })
for (const { obj } of allObjects()) if (obj._canvas) units.push({ z: obj.z || 0, el: obj._canvas, vis: obj.visible !== false })
units.sort((a, b) => a.z - b.z)
for (const u of units) {
if (!u.el) continue
S.canvasStack.insertBefore(u.el, S.strokeCanvas)
u.el.style.display = u.vis ? 'block' : 'none'
}
}
/** 获取活跃位图图层 */
export function getActiveLayer() {
return S.layers.find(l => l.id === S.activeLayerId) || null
}
/** 获取活跃位图图层的 2d context(画笔/橡皮操作目标) */
export function getActiveCtx() {
const layer = getActiveLayer()
return layer && !layer.locked ? layer.ctx : null
}
/** 清理所有画布/图层选择态,保证不同工具和图层之间互斥 */
export function clearSelection({ keepBitmap = false } = {}) {
if (!keepBitmap) S.selectedLayerId = null
S.selectedTextId = null
S.selectedShapeId = null
S.textDrag = null
S.shapeDrag = null
S.bitmapDrag = null
}
/** 确定源图/源画布的取样框:内容盒 _srcBox 优先,其次整图 image,再其次整张 sourceCanvas;无可用源返回 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()
}
/** 按图层当前的源(原图 / 源画布 / 内容盒)与旋转角重绘该图层 */
export function redrawBitmapLayer(layer) {
if (!layer || !layer.ctx) return
layer.ctx.clearRect(0, 0, S.imgW, S.imgH)
paintTransformed(layer, resolveSourceBox(layer))
}
export 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
}
// isDrawableLayer / restorePath / needsPixelSnapshot 统一由 shared/layer-logic.js 提供
// (快照端与恢复端必须共用同一判定,可单测守护)
/** 内容包围盒(非透明像素范围),带缓存;step=2 降低扫描开销 */
function layerBounds(layer) {
if (!layer || !layer.ctx || !layer.canvas) return null
if (layer._bounds !== undefined) 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 }
}
export function hitBitmapLayer(pos) {
const layers = [...S.layers].sort((a, b) => (a.z || 0) - (b.z || 0))
const hitRect = (layer) => {
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]
return lp[0] >= layer.x && lp[0] <= layer.x + layer.w && lp[1] >= layer.y && lp[1] <= layer.y + layer.h
}
const usable = (layer) => layer && layer.visible !== false && !layer.locked
// 第一轮:绘制类图层按像素命中(点内容才算,避免被上层图片层拦截)
for (let i = layers.length - 1; i >= 0; i--) {
const layer = layers[i]
if (!usable(layer)) continue
if (!isDrawableLayer(layer)) continue
if (!hitRect(layer)) continue
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]
const px = Math.round(lp[0]), py = Math.round(lp[1])
if (px < 0 || py < 0 || px >= layer.canvas.width || py >= layer.canvas.height) continue
try {
const d = layer.ctx.getImageData(px, py, 1, 1).data
if (d[3] > 8) return layer
} catch (e) { return layer }
}
// 第二轮:图片类图层按矩形命中
for (let i = layers.length - 1; i >= 0; i--) {
const layer = layers[i]
if (!usable(layer) || !layer.transformable) continue
if (hitRect(layer)) return layer
}
return null
}
export 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)
}
/** 任意矩形的 8 个控制点(含旋转)*/
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
}
export 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()
}
}
export 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 = undefined
} 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 = undefined
redrawBitmapLayer(layer)
}
/** 切换画笔/橡皮作用的活动图层 */
export function setActiveLayer(id) {
S.activeLayerId = id
S.selectedLayerId = id
S.selectedTextId = null
S.selectedShapeId = null
S.textDrag = null
S.shapeDrag = null
renderLayerPanel()
renderObjects()
}
/** 添加位图图层(导入图片) — 启动放置流程,先调整大小/位置再确认 */
export function addBitmapLayer(img) {
startImagePlacement(img)
}
/** 新建空白图层 */
export function addBlankLayer() { // 创建可独立编辑的位图图层
const id = 'L' + Date.now() + Math.floor(Math.random() * 1000)
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)
// 重排 z 序
S.layers.forEach((l, i) => { l.z = i })
// 如果删除的是活跃图层,切到最后一个
if (S.activeLayerId === id) {
S.activeLayerId = S.layers[S.layers.length - 1].id
}
reorderLayerCanvas()
renderLayerPanel()
}
// ============ 矢量对象独立画布(位图/矢量统一排序) ============
function vecCanvasFor(obj) {
if (!obj._canvas || !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
}
export function removeVecCanvas(obj) {
if (obj && obj._canvas) {
if (obj._canvas.parentNode) obj._canvas.parentNode.removeChild(obj._canvas)
obj._canvas = null
obj._ctx = null
}
}
export function purgeVectorCanvases() {
for (const t of S.textLayers) removeVecCanvas(t)
for (const sh of S.shapeLayers) removeVecCanvas(sh)
}
export 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
}
/** 更新位图图层尺寸;位置始终由 canvas-stack 统一管理。 */
export 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)
}
export 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'
}
}
// ============ 图层面板 UI ============
export function renderLayerPanel() {
const list = runtime.el.querySelector('.iwb-editor-layer-list')
if (!list) return
// 收集所有图层项(位图 + 矢量对象),按 z 序倒序(最上层在最前)
const items = []
// 位图图层
for (const layer of S.layers) {
items.push({
id: layer.id,
type: 'bitmap',
name: layer.name,
opacity: layer.opacity,
visible: layer.visible,
z: layer.z,
color: layer.color || S.color,
lineWidth: layer.lineWidth || S.brushSize,
active: layer.id === (S.selectedLayerId || S.activeLayerId),
locked: !!layer.locked,
canDelete: S.layers.length > 1
})
}
// 矢量对象(文字 + 形状),按 z 序排序
const vectorObjs = allObjects()
for (const { kind, obj } of vectorObjs) {
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),
locked: !!obj.locked,
canDelete: true
})
}
// 按 z 序倒序排列(最上层在最前)
items.sort((a, b) => b.z - a.z)
let html = ''
for (const item of items) {
const activeClass = item.active ? ' active' : ''
const visClass = item.visible ? '' : ' hidden'
// SVG 图标
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.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 = [...S.layers.map(obj => ({ kind: 'bitmap', obj })), ...allObjects()]
.sort((a, b) => (a.obj.z || 0) - (b.obj.z || 0))
const from = all.findIndex(item => item.obj.id === dragId)
let to = all.findIndex(item => item.obj.id === targetId)
if (from < 0 || to < 0) return
const [moved] = all.splice(from, 1)
to = all.findIndex(item => item.obj.id === targetId)
all.splice(to, 0, moved)
saveSnapshot()
all.forEach((item, index) => { item.obj.z = index })
S.zCounter = Math.max(S.zCounter, all.length - 1)
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') {
S.selectedLayerId = null
S.selectedShapeId = null
S.selectedTextId = id
S.textDrag = null
S.shapeDrag = null
S.bitmapDrag = null
renderObjects()
renderLayerPanel()
} else if (type === 'shape') {
S.selectedLayerId = null
S.selectedTextId = null
S.selectedShapeId = id
S.textDrag = null
S.shapeDrag = null
S.bitmapDrag = null
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() }
})
})
}
/** 显隐切换按钮:位图直接切 visible,文字/形状切对象 visible 并重绘 */
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 }
}
})
})
}
/** 锁定/解锁按钮:切换对象 locked 并存快照 */
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()
}
})
})
}
+646
View File
@@ -0,0 +1,646 @@
/* objects.js - 文字、形状、钢笔与选择手柄
* 节:文字图层、形状图层、钢笔二次编辑、文字输入框。
* 矢量对象统一走 S.textLayers / S.shapeLayers 与 S.zCounter 排序,
* 渲染到 S.textCanvas(layers.js 负责它在图层栈里的位置)。
*/
'use strict'
import { S, runtime } from './state.js'
import { boxCorners, clamp, drawRotationHandles, hitRotationHandle, rotPt, unrotPt } from './viewport.js'
import { clearOverlay, drawCropPreview } from './crop.js'
import { drawBitmapSelection, drawVectorToCanvas, removeVecCanvas, renderLayerPanel, reorderLayerCanvas } from './layers.js'
import { drawPlacementPreview } from './placement.js'
import { drawShape } from './tools.js'
import { saveSnapshot, snapshotState } from './history.js'
import { updateLayerUI } from './events.js'
import { isDrawableLayer } from '../vendor/layer-logic.js'
// ============ 文字图层 ============
export const TEXT_FONT = (size) => 'bold ' + size + 'px sans-serif'
export 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 }
}
export function getSelectedText() {
return S.textLayers.find(t => t.id === S.selectedTextId) || null
}
export 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
}
export 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
}
// ============ 形状图层 ============
export 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) }
}
export 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)
}
export 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
}
/** 所有对象(文字 + 形状)按 z 升序排列 */
export 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
}
export function sortLayersByZ() {
const cmp = (a, b) => (a.z || 0) - (b.z || 0)
S.textLayers.sort(cmp)
S.shapeLayers.sort(cmp)
}
export function hitAnyObject(pos) {
const list = allObjects()
for (let i = list.length - 1; i >= 0; i--) {
const { kind, obj } = list[i]
if (obj.visible === false) continue
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]
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 { kind, obj }
}
} else if (hitShapeObj(pos, obj, true)) {
return { kind, obj }
}
}
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
}
/** 图层顺序调整 */
export 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) return
if (sel.obj.locked) return
const all = [...S.layers.map(o => ({ kind: 'bitmap', obj: o })), ...allObjects()].sort((a, b) => (a.obj.z || 0) - (b.obj.z || 0))
const idx = all.findIndex(o => o.obj === sel.obj)
if (idx < 0) return
if ((dir === 'up' || dir === 'top') && idx === all.length - 1) return
if ((dir === 'down' || dir === 'bottom') && idx === 0) return
saveSnapshot()
if (dir === 'up') {
const t = all[idx + 1].obj
const tz = t.z
t.z = sel.obj.z
sel.obj.z = tz
} else if (dir === 'down') {
const t = all[idx - 1].obj
const tz = t.z
t.z = sel.obj.z
sel.obj.z = tz
} else if (dir === 'top') {
sel.obj.z = all[all.length - 1].obj.z + 1
} else {
sel.obj.z = all[0].obj.z - 1
}
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
}
export 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
}
export 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)
}
export 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()
}
/** 重绘对象层 + 选中态 */
export 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()
}
// ============ 钢笔二次编辑(移动/添加/删除节点) ============
export function getPenEditingShape() {
if (!S.penEditId) return null
return S.shapeLayers.find(sh => sh.id === S.penEditId && sh.type === 'pen') || null
}
export 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()
}
export function exitPenEdit() {
S.penEditId = null
S.penDragPt = -1
S.penDragBase = null
S.penDragPending = null
renderObjects()
renderLayerPanel()
}
export 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
}
export 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()
}
// ============ 文字输入框 ============
export 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
}
export function hideTextInput() {
const input = runtime.el.querySelector('.iwb-editor-text-input')
if (input) {
// 必须先 blur:只隐藏不清焦点的话,焦点还留在隐藏的 input 上,
// 之后按 Esc 会被 isTyping() 当成"正在输入文字"吞掉(清不掉选中态)
if (document.activeElement === input) input.blur()
input.style.display = 'none'
input.value = ''
}
S.textEditingId = null
}
export 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() * 1000),
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)
S.selectedTextId = layer.id
renderObjects()
committed = true
}
hideTextInput()
return committed
}
export 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()
}
export 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()
}
}
export 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()
}
}
export function beginShapeHandleDrag(handle, pos) {
const sh = getSelectedShape()
if (!sh || sh.locked) return
S.shapeDrag = {
mode: 'handle', handle,
start: pos,
shape: { ...sh },
pending: snapshotState()
}
}
+251
View File
@@ -0,0 +1,251 @@
/* placement.js - 导入图片的放置(先调大小/位置再确认)
* 节:图片放置(导入图片时先调整大小/位置)。
* 状态挂在 S.placingImage / placingHandle / placingStart 上,
* 确认后由 confirmImagePlacement 把图片落成新的位图图层(调 layers.js)。
*/
'use strict'
import { S } from './state.js'
import { boxCorners, drawRotationHandles, hitRotationHandle, rotPt, unrotPt } from './viewport.js'
import { clearOverlay } from './crop.js'
import { createLayerCanvas, redrawBitmapLayer, renderLayerPanel, reorderLayerCanvas, setActiveLayer, updateLayerCanvasStyles } from './layers.js'
import { saveSnapshot } from './history.js'
import { updateCursor } from './events.js'
// ============ 图片放置(导入图片时先调整大小/位置) ============
/** 启动图片放置:默认尺寸为图片原大但不超过画布 50%,居中 */
export function startImagePlacement(img) {
const iw = img.naturalWidth || img.width
const ih = img.naturalHeight || img.height
// 默认大小:不超过画布宽高的 50%
const maxW = S.imgW * 0.5
const maxH = S.imgH * 0.5
const ratio = Math.min(maxW / iw, maxH / ih, 1)
let w = Math.round(iw * ratio)
let h = Math.round(ih * ratio)
if (w < 10) w = 10
if (h < 10) h = 10
// 居中
const x = Math.round((S.imgW - w) / 2)
const y = Math.round((S.imgH - h) / 2)
S.placingImage = { img, x, y, w, h, rotation: 0 }
S.placingHandle = null
S.placingStart = null
S.drawCanvasCursor('move')
drawPlacementPreview()
}
/** 确认图片放置:创建新位图图层并绘制图片 */
export 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()
// 创建图层
const id = 'L' + Date.now() + Math.floor(Math.random() * 1000)
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: placementRotation, transformable: true,
canvas,
ctx,
opacity: 1,
visible: true,
locked: false,
z: S.layers.length
}
redrawBitmapLayer(layer)
saveSnapshot()
S.layers.push(layer)
reorderLayerCanvas()
setActiveLayer(id)
updateLayerCanvasStyles()
renderLayerPanel()
updateCursor()
}
/** 取消图片放置 */
export function cancelImagePlacement() {
S.placingImage = null
S.placingHandle = null
S.placingStart = null
clearOverlay()
updateCursor()
}
/** 放置预览:在 overlay 上画图片 + 手柄 */
export 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([])
// 8 个缩放手柄(旋转后位置)
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()
}
export 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
}
/** 检查是否在放置矩形内 */
export 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
}
/** 放置手柄拖拽:根据手柄调整图片大小 */
export 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 }
// Shift 键 = 等比缩放
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
}
+82
View File
@@ -0,0 +1,82 @@
/* state.js - 编辑器唯一状态所有者
* 持有 S(全局状态对象)、ZOOM_* 常量,以及 runtime(可变持有对象)。
* 约定:ES 模块 import 绑定不可重新赋值,所以编辑器根节点 el 不用
* `export let el`,而是放在 runtime.el 里,各模块统一读写 runtime.el。
* 本模块不 import 任何编辑器内部模块(保持叶子节点,避免循环 TDZ)。
*/
'use strict'
export const ZOOM_MIN = 0.1
export const ZOOM_MAX = 10
export const ZOOM_STEP = 1.15
// ============ 状态 ============
export const 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
}
export const runtime = { el: null }
+372
View File
@@ -0,0 +1,372 @@
/* tools.js - 画笔、橡皮、吸管与合成画布
* 节:绘制工具、合成画布(吸管取样 / 导出 / 裁剪共用)。
* 约定:brushStampCache 是模块级缓存,只在本模块内重建;
* getCompositeCanvas 把所有可见图层+矢量对象合成到一张画布,
* 吸管/导出/裁剪共用它。
*/
'use strict'
import { S, runtime } from './state.js'
import { allObjects, commitTextInput, getSelectedShape, getSelectedText, renderObjects, shapeBounds } from './objects.js'
import { cancelCrop, clearOverlay, hideCropBar, showCropBar, updateCropInfo } from './crop.js'
import { cancelImagePlacement } from './placement.js'
import { clamp } from './viewport.js'
import { getActiveCtx, getActiveLayer, renderLayerPanel } from './layers.js'
import { saveSnapshot } from './history.js'
import { updateBrushParamUI, updateColorUI, updateToolUI } from './events.js'
import { isDrawableLayer } from '../vendor/layer-logic.js'
import { hexToRgb, rgbToHex } from '../vendor/image-math.js'
// ============ 绘制工具 ============
// hexToRgb / rgbToHex / parseRatio 统一由 shared/image-math.js 提供(可单测)
let brushStampCache = { key: '', canvas: null }
/** 软边笔刷章:径向渐变离屏 canvas */
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
}
/** 画笔/橡皮一笔的一段:画在 strokeCanvas(全不透明),透明度由 endStroke 合成时承担
* 橡皮用白色(destination-out 合成时只取 alpha 通道) */
export 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
}
export function eraseSegment(x1, y1, x2, y2) {
const ctx = getActiveCtx()
if (!ctx) return
ctx.save()
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 = undefined
}
export 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
}
/** 结束一笔:按透明度一次性合成进活跃图层(画笔=正常合成,橡皮=destination-out) */
export function endStroke() {
for (const l of S.layers) l._bounds = undefined
const ctx = getActiveCtx()
if (!ctx) return
ctx.save()
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
}
/** 按形状对象绘制(矩形/箭头),预览与最终渲染共用 */
export 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
}
/** 圆形笔刷光标 */
export function drawToolRing(pos) {
clearOverlay()
const ctx = 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()
}
// ============ 合成画布(吸管取样 / 导出 / 裁剪共用) ============
/** 合成所有可见图层到一个临时 canvas */
export function getCompositeCanvas() {
const c = document.createElement('canvas')
c.width = S.imgW
c.height = S.imgH
const cx = c.getContext('2d', { willReadFrequently: true })
const units = []
for (const l of S.layers) units.push({ z: l.z, el: l.canvas, vis: l.visible, op: l.opacity })
for (const { obj } of allObjects()) if (obj._canvas) units.push({ z: obj.z || 0, el: obj._canvas, vis: obj.visible !== false, op: obj.opacity != null ? obj.opacity : 1 })
units.sort((a, b) => a.z - b.z)
cx.globalAlpha = 1
for (const u of units) {
if (!u.vis) continue
cx.globalAlpha = u.op == null ? 1 : u.op
cx.drawImage(u.el, 0, 0)
}
cx.globalAlpha = 1
return c
}
/** 吸管取样用的合成画布缓存 */
function getPickerComposite() {
if (!S.pickerComposite) {
S.pickerComposite = getCompositeCanvas().getContext('2d', { willReadFrequently: true })
}
return S.pickerComposite
}
/** 取画布坐标处的合成像素颜色 */
export 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
}
}
/** 吸管悬停预览浮窗 */
export 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'
}
export function hidePickerTip() {
const tip = runtime.el.querySelector('.iwb-editor-picker-tip')
if (tip) tip.style.display = 'none'
}
/** 取色完成:切回吸管激活前的工具 */
export 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()
}
/** 统一颜色应用:设置当前色 + 同步选中文字/形状颜色 */
export 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()
}
}
/** 切换工具(工具栏按钮、快捷键、调色板吸色共用)。保留同类形状选中以便继续编辑。 */
export 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
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()
}
+279
View File
@@ -0,0 +1,279 @@
/* viewport.js - 画布尺寸、缩放平移、旋转辅助与坐标换算
* 节:画布设置、旋转辅助、坐标。
* 约定:所有屏幕坐标 <-> 图片坐标的换算都过 getPos/rotPt/unrotPt,
* 缩放状态只写 S.zoom / S.viewX / S.viewY。
*/
'use strict'
import { S, ZOOM_MAX, ZOOM_MIN } from './state.js'
import { bindCanvasEvents, updateZoomUI } from './events.js'
import { clearOverlay } from './crop.js'
import { createLayerCanvas, purgeVectorCanvases, renderLayerPanel, styleVectorViewport } from './layers.js'
import { getSelectedShape, getSelectedText, renderObjects, shapeBounds, textBounds } from './objects.js'
// ============ 画布设置 ============
function syncOverlayCanvas() {
const pad = S.overlayPad || 0
const scale = S.imgW ? (S.fitW * S.zoom) / S.imgW : 1
S.overlayCanvas.style.left = '0px'
S.overlayCanvas.style.top = '0px'
S.overlayCanvas.style.width = Math.round((S.imgW + pad * 2) * scale) + 'px'
S.overlayCanvas.style.height = Math.round((S.imgH + pad * 2) * scale) + 'px'
}
export function setupCanvas(img) {
purgeVectorCanvases()
// 清除旧的动态图层 canvas
for (const layer of S.layers) {
if (layer.canvas.parentNode) layer.canvas.parentNode.removeChild(layer.canvas)
}
S.layers = []
// 设置工具 canvas 尺寸
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))
S.overlayCanvas.width = S.imgW + S.overlayPad * 2
S.overlayCanvas.height = S.imgH + S.overlayPad * 2
S.overlayCtx.setTransform(1, 0, 0, 1, S.overlayPad, S.overlayPad)
// 创建图层 1: 原图
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
})
// 创建图层 2: 画笔标注(空透明层)
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)
}
/**
* 应用当前 zoom 与平移位置到画布显示尺寸与位置(自由平移,无边界限制)。
* @param {object} anchor 可选 { mx, my, px, py }:缩放锚点
*/
function applyView(anchor) {
const w = Math.round(S.fitW * S.zoom)
const h = Math.round(S.fitH * S.zoom)
// 更新所有 canvas 的显示尺寸(位图图层 + 工具层)
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'
}
// 显式固定 stack 尺寸,保证统一坐标基准始终可测量,新增/隐藏图层不会触发布局偏移。
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 !== undefined) {
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()
}
/** 设置画布平移位置(自由坐标,无边界限制) */
export 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
// 让原图左上角仍对应 viewX/viewY,外围 padding 不参与画布平移坐标。
stack.style.transform = `translate3d(${Math.round(x - pad * scale)}px, ${Math.round(y - pad * scale)}px, 0)`
}
/** 以指定屏幕坐标(wrap 内)为中心缩放 */
export 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 })
}
export function setZoomFit() {
S.zoom = 1
S.viewX = null
applyView()
}
export function clamp(v, min, max) { return Math.max(min, Math.min(max, v)) }
// ============ 旋转辅助 ============
export 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]
}
export 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, 0.0001)
return [[b.x, b.y], [b.x + b.w, b.y], [b.x + b.w, b.y + b.h], [b.x, b.y + b.h]].map(c => {
const dx = c[0] - cx, dy = c[1] - cy, len = Math.hypot(dx, dy) || 1
return [c[0] + dx / len * d, c[1] + dy / len * d]
})
}
/** 命中旋转手柄(传局部坐标点) */
export function hitRotationHandle(lp, b) {
const pts = rotationHandlesLocal(b)
const R = Math.max(13 / Math.max(S.zoom, 0.0001), 9)
for (const pt of pts) {
if (Math.hypot(lp[0] - pt[0], lp[1] - pt[1]) < R) return true
}
return false
}
/** 绘制四个角外侧的圆弧旋转手柄 */
export 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, 0.0001), 6)
ctx.save()
ctx.strokeStyle = '#e8a735'
ctx.lineWidth = 2 / Math.max(S.zoom, 0.0001)
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()
}
export const 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'
/** 指针是否悬停在当前选中对象(或放置中图片)的旋转手柄上 */
export 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
}
export 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))
}
// ============ 坐标 ============
export function getPos(e) {
// 统一使用 stack 的边界作为坐标基准。图层 canvas 可能被隐藏,或在
// 插入/重排时暂时不参与布局;以具体图层 boundingRect 计算会造成左移。
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, 0.0001) - pad,
y: (e.clientY - rect.top) / Math.max(scale, 0.0001) - pad
}
}
+17
View File
@@ -0,0 +1,17 @@
/* 打包入口(esbuild → IIFE)。
*
* 顺序要求:先 import 编辑器模块 —— 它在模块顶层把 window.__iwbEditor 挂好(编辑器自带约定);
* glue.js 只在模块顶层声明函数,不读 window,故无 TDZ/顺序风险。
*
* manifest 不放在这里:esbuild 的打印器会把单引号改写成双引号,而 scripts/validate.mjs
* 只认单引号。manifest 走 build-plugin.mjs 的 banner 通道(原样写入),注册调用走 footer 通道。
*/
'use strict'
import './editor/index.js'
import editorCss from './editor.css'
import { createGlue } from './glue.js'
;(typeof window !== 'undefined' ? window : globalThis).__IWB_ANNOTATE_FACTORY__ = function (ctx) {
return createGlue(ctx, editorCss)
}
+125
View File
@@ -0,0 +1,125 @@
/* 宿主胶水:把 window.__iwbEditor(从 iwb-plaus 扩展移植)接到 IWBPluginHost 的 ctx 上。
*
* 数据流(全部走公开契约,不碰宿主内部实现):
* nodeActions.run(node) → ctx.canvas.getNodeImage(node.id) → __iwbEditor.open()
* → onResult(blob|dataURL, mode) → mode==='replace' ? ctx.canvas.setNodeImage
* : ctx.canvas.createImageNode
*
* 注意 mode 字面量来自编辑器 events.js 的按钮绑定,是 'newNode' / 'replace'(不是 'new')。
* CSP:宿主 style-src 允许 'unsafe-inline',故样式用运行时 <style> 注入;
* img-src 允许 data:/blob:,编辑器内部 blob URL 可用。
*/
'use strict'
export 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)
})
}
// 编辑器优先给 Blob(省 44MB base64 堆驻留),toBlob 失败时才退化成 dataURL。
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) {
// getNodeImage 对跨域 http 图只返回 { url }(画布读像素会污染),v1 明确拒绝并给出可操作提示。
throw new Error(image && image.url
? '该节点是远程图片,暂不支持标注(请先转存为本地位图)'
: '该节点没有可编辑的图片')
}
ensureStyle()
return new Promise(function (resolve, reject) {
let settled = false
const settle = function (fn) { if (!settled) { settled = true; fn() } }
Promise.resolve(editor.open({
imageBase64: image.dataUrl,
imageName: baseName(node) + '.png',
onError: function (message) {
settle(function () { reject(new Error(String(message || '编辑失败'))) })
},
onResult: function (out, mode) {
imageToDataUrl(out).then(function (dataUrl) {
const replaced = mode === 'replace'
const ok = replaced
? ctx.canvas.setNodeImage(id, dataUrl)
: Boolean(ctx.canvas.createImageNode({ dataUrl: 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) })
})
})
})
}
// 图片承载类型:ref / out(参考实现同款)+ gen / layer(宿主 isImageProducer 认定的产图类型)。
function appliesTo(node) {
if (!node) return false
return node.type === 'ref' || node.type === 'out' || node.type === 'gen' || node.type === 'layer'
}
ctx.nodeActions.register({
id: 'annotate-node',
title: '标注 / 修图',
icon: 'layer',
appliesTo: appliesTo,
run: function (node) { return openEditor(node) },
})
ctx.commands.register({
id: 'annotate-selected',
title: '标注 / 修图:选中节点',
icon: 'layer',
run: function () {
const selected = ctx.canvas.getSelectedNode()
if (!selected) return Promise.reject(new Error('请先选中一个带图的节点'))
return openEditor(selected)
},
})
return {
dispose: function () { /* 编辑器自带 close() 与像素释放,这里无额外订阅需要解绑 */ },
}
}
+15
View File
@@ -0,0 +1,15 @@
// 手写 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: '__PLUGIN_VERSION__',
apiVersion: 1,
capabilities: ['commands', 'nodeActions', 'canvas', 'canvasWrite'],
}
+9
View File
@@ -0,0 +1,9 @@
// 手写注册尾部(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)
+52
View File
@@ -0,0 +1,52 @@
/* 与 canvas/DOM 无关的纯计算,抽出来是为了能被单元测试直接覆盖 */
/** #rgb / #rrggbb → {r,g,b}(0~255) */
export 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
}
}
/** {r,g,b} / (r,g,b) → #rrggbb */
export 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)}`
}
/** 裁剪比例字符串 "16:9" / "free" → 数值 (w/h);非法返回 0(表示不限制) */
export 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
}
/**
* 把内容等比缩放并居中放进 box(白底大图 / 覆盖布局共用)
* 内容最长边 = min(boxW, boxH) * ratio
* @returns {{x:number,y:number,w:number,h:number,scale:number}} 无效输入返回全 0 矩形
*/
export function fitRect(srcW, srcH, boxW, boxH, ratio = 1) {
if (!(srcW > 0) || !(srcH > 0) || !(boxW > 0) || !(boxH > 0)) {
return { x: 0, y: 0, w: 0, h: 0, scale: 0 }
}
const r = Math.max(0.01, Math.min(1, ratio))
const maxLen = Math.min(boxW, boxH) * r
const scale = Math.min(maxLen / srcW, maxLen / srcH)
const w = srcW * scale
const h = srcH * scale
return { x: (boxW - w) / 2, y: (boxH - h) / 2, w, h, scale }
}
/** 通用 clamp */
export function clamp(v, min, max) {
return Math.max(min, Math.min(max, v))
}
+41
View File
@@ -0,0 +1,41 @@
/* 图层恢复路径判定 —— 快照端与恢复端共用的唯一真源
* 快照端(editor.js snapshotState)用它决定"要不要拍这份像素",
* 恢复端(editor.js restoreState)用它决定"要不要读这份像素"。
* 两边必须永远一致,否则会出现"快照没拍、恢复却要读"的数据丢失。
*/
/**
* 绘制类图层(画笔标注 / 空白图层):非原图、且没有绑定图片的光栅层
* @param {{id?:string, image?:unknown}} layer
*/
export function isDrawableLayer(layer) {
return !!layer && layer.id !== 'base' && !layer.image
}
/**
* 恢复该图层时走哪条路径
* 'redraw':按 image/sourceCanvas 几何重绘,快照里的 bm.data 永远不会被读取
* —— 这类图层的像素是白存的字节(通常是最大的原图层)
* 'pixels':依赖 putImageData(bm.data),快照必须保留像素
*
* 注意 sourceCanvas 的语义:恢复流程对绘制类图层会先清空 sourceCanvas,
* 因此这里对 drawable 图层一律按"没有 sourceCanvas"处理。
*
* @param {{id?:string, image?:unknown, sourceCanvas?:unknown, transformable?:boolean}} layer
* @returns {'redraw'|'pixels'}
*/
export function restorePath(layer) {
if (!layer) return 'pixels'
const sourceCanvas = isDrawableLayer(layer) ? null : layer.sourceCanvas
if (layer.transformable && (layer.image || sourceCanvas)) return 'redraw'
return 'pixels'
}
/**
* 快照是否可以跳过该图层的像素
* 与 restorePath 完全等价,单独命名是为了让快照端的意图更直白。
*/
export function needsPixelSnapshot(layer) {
return restorePath(layer) === 'pixels'
}
File diff suppressed because it is too large. Load diff
+481
View File
@@ -0,0 +1,481 @@
{
"name": "@iwb-plugin/workspace",
"version": "1.0.0",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "@iwb-plugin/workspace",
"version": "1.0.0",
"devDependencies": {
"esbuild": "^0.24.2"
}
},
"node_modules/@esbuild/aix-ppc64": {
"version": "0.24.2",
"resolved": "https://registry.npmjs.org/@esbuild/aix-ppc64/-/aix-ppc64-0.24.2.tgz",
"integrity": "sha512-thpVCb/rhxE/BnMLQ7GReQLLN8q9qbHmI55F4489/ByVg2aQaQ6kbcLb6FHkocZzQhxc4gx0sCk0tJkKBFzDhA==",
"cpu": [
"ppc64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"aix"
],
"engines": {
"node": ">=18"
}
},
"node_modules/@esbuild/android-arm": {
"version": "0.24.2",
"resolved": "https://registry.npmjs.org/@esbuild/android-arm/-/android-arm-0.24.2.tgz",
"integrity": "sha512-tmwl4hJkCfNHwFB3nBa8z1Uy3ypZpxqxfTQOcHX+xRByyYgunVbZ9MzUUfb0RxaHIMnbHagwAxuTL+tnNM+1/Q==",
"cpu": [
"arm"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"android"
],
"engines": {
"node": ">=18"
}
},
"node_modules/@esbuild/android-arm64": {
"version": "0.24.2",
"resolved": "https://registry.npmjs.org/@esbuild/android-arm64/-/android-arm64-0.24.2.tgz",
"integrity": "sha512-cNLgeqCqV8WxfcTIOeL4OAtSmL8JjcN6m09XIgro1Wi7cF4t/THaWEa7eL5CMoMBdjoHOTh/vwTO/o2TRXIyzg==",
"cpu": [
"arm64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"android"
],
"engines": {
"node": ">=18"
}
},
"node_modules/@esbuild/android-x64": {
"version": "0.24.2",
"resolved": "https://registry.npmjs.org/@esbuild/android-x64/-/android-x64-0.24.2.tgz",
"integrity": "sha512-B6Q0YQDqMx9D7rvIcsXfmJfvUYLoP722bgfBlO5cGvNVb5V/+Y7nhBE3mHV9OpxBf4eAS2S68KZztiPaWq4XYw==",
"cpu": [
"x64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"android"
],
"engines": {
"node": ">=18"
}
},
"node_modules/@esbuild/darwin-arm64": {
"version": "0.24.2",
"resolved": "https://registry.npmjs.org/@esbuild/darwin-arm64/-/darwin-arm64-0.24.2.tgz",
"integrity": "sha512-kj3AnYWc+CekmZnS5IPu9D+HWtUI49hbnyqk0FLEJDbzCIQt7hg7ucF1SQAilhtYpIujfaHr6O0UHlzzSPdOeA==",
"cpu": [
"arm64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"darwin"
],
"engines": {
"node": ">=18"
}
},
"node_modules/@esbuild/darwin-x64": {
"version": "0.24.2",
"resolved": "https://registry.npmjs.org/@esbuild/darwin-x64/-/darwin-x64-0.24.2.tgz",
"integrity": "sha512-WeSrmwwHaPkNR5H3yYfowhZcbriGqooyu3zI/3GGpF8AyUdsrrP0X6KumITGA9WOyiJavnGZUwPGvxvwfWPHIA==",
"cpu": [
"x64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"darwin"
],
"engines": {
"node": ">=18"
}
},
"node_modules/@esbuild/freebsd-arm64": {
"version": "0.24.2",
"resolved": "https://registry.npmjs.org/@esbuild/freebsd-arm64/-/freebsd-arm64-0.24.2.tgz",
"integrity": "sha512-UN8HXjtJ0k/Mj6a9+5u6+2eZ2ERD7Edt1Q9IZiB5UZAIdPnVKDoG7mdTVGhHJIeEml60JteamR3qhsr1r8gXvg==",
"cpu": [
"arm64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"freebsd"
],
"engines": {
"node": ">=18"
}
},
"node_modules/@esbuild/freebsd-x64": {
"version": "0.24.2",
"resolved": "https://registry.npmjs.org/@esbuild/freebsd-x64/-/freebsd-x64-0.24.2.tgz",
"integrity": "sha512-TvW7wE/89PYW+IevEJXZ5sF6gJRDY/14hyIGFXdIucxCsbRmLUcjseQu1SyTko+2idmCw94TgyaEZi9HUSOe3Q==",
"cpu": [
"x64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"freebsd"
],
"engines": {
"node": ">=18"
}
},
"node_modules/@esbuild/linux-arm": {
"version": "0.24.2",
"resolved": "https://registry.npmjs.org/@esbuild/linux-arm/-/linux-arm-0.24.2.tgz",
"integrity": "sha512-n0WRM/gWIdU29J57hJyUdIsk0WarGd6To0s+Y+LwvlC55wt+GT/OgkwoXCXvIue1i1sSNWblHEig00GBWiJgfA==",
"cpu": [
"arm"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"linux"
],
"engines": {
"node": ">=18"
}
},
"node_modules/@esbuild/linux-arm64": {
"version": "0.24.2",
"resolved": "https://registry.npmjs.org/@esbuild/linux-arm64/-/linux-arm64-0.24.2.tgz",
"integrity": "sha512-7HnAD6074BW43YvvUmE/35Id9/NB7BeX5EoNkK9obndmZBUk8xmJJeU7DwmUeN7tkysslb2eSl6CTrYz6oEMQg==",
"cpu": [
"arm64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"linux"
],
"engines": {
"node": ">=18"
}
},
"node_modules/@esbuild/linux-ia32": {
"version": "0.24.2",
"resolved": "https://registry.npmjs.org/@esbuild/linux-ia32/-/linux-ia32-0.24.2.tgz",
"integrity": "sha512-sfv0tGPQhcZOgTKO3oBE9xpHuUqguHvSo4jl+wjnKwFpapx+vUDcawbwPNuBIAYdRAvIDBfZVvXprIj3HA+Ugw==",
"cpu": [
"ia32"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"linux"
],
"engines": {
"node": ">=18"
}
},
"node_modules/@esbuild/linux-loong64": {
"version": "0.24.2",
"resolved": "https://registry.npmjs.org/@esbuild/linux-loong64/-/linux-loong64-0.24.2.tgz",
"integrity": "sha512-CN9AZr8kEndGooS35ntToZLTQLHEjtVB5n7dl8ZcTZMonJ7CCfStrYhrzF97eAecqVbVJ7APOEe18RPI4KLhwQ==",
"cpu": [
"loong64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"linux"
],
"engines": {
"node": ">=18"
}
},
"node_modules/@esbuild/linux-mips64el": {
"version": "0.24.2",
"resolved": "https://registry.npmjs.org/@esbuild/linux-mips64el/-/linux-mips64el-0.24.2.tgz",
"integrity": "sha512-iMkk7qr/wl3exJATwkISxI7kTcmHKE+BlymIAbHO8xanq/TjHaaVThFF6ipWzPHryoFsesNQJPE/3wFJw4+huw==",
"cpu": [
"mips64el"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"linux"
],
"engines": {
"node": ">=18"
}
},
"node_modules/@esbuild/linux-ppc64": {
"version": "0.24.2",
"resolved": "https://registry.npmjs.org/@esbuild/linux-ppc64/-/linux-ppc64-0.24.2.tgz",
"integrity": "sha512-shsVrgCZ57Vr2L8mm39kO5PPIb+843FStGt7sGGoqiiWYconSxwTiuswC1VJZLCjNiMLAMh34jg4VSEQb+iEbw==",
"cpu": [
"ppc64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"linux"
],
"engines": {
"node": ">=18"
}
},
"node_modules/@esbuild/linux-riscv64": {
"version": "0.24.2",
"resolved": "https://registry.npmjs.org/@esbuild/linux-riscv64/-/linux-riscv64-0.24.2.tgz",
"integrity": "sha512-4eSFWnU9Hhd68fW16GD0TINewo1L6dRrB+oLNNbYyMUAeOD2yCK5KXGK1GH4qD/kT+bTEXjsyTCiJGHPZ3eM9Q==",
"cpu": [
"riscv64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"linux"
],
"engines": {
"node": ">=18"
}
},
"node_modules/@esbuild/linux-s390x": {
"version": "0.24.2",
"resolved": "https://registry.npmjs.org/@esbuild/linux-s390x/-/linux-s390x-0.24.2.tgz",
"integrity": "sha512-S0Bh0A53b0YHL2XEXC20bHLuGMOhFDO6GN4b3YjRLK//Ep3ql3erpNcPlEFed93hsQAjAQDNsvcK+hV90FubSw==",
"cpu": [
"s390x"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"linux"
],
"engines": {
"node": ">=18"
}
},
"node_modules/@esbuild/linux-x64": {
"version": "0.24.2",
"resolved": "https://registry.npmjs.org/@esbuild/linux-x64/-/linux-x64-0.24.2.tgz",
"integrity": "sha512-8Qi4nQcCTbLnK9WoMjdC9NiTG6/E38RNICU6sUNqK0QFxCYgoARqVqxdFmWkdonVsvGqWhmm7MO0jyTqLqwj0Q==",
"cpu": [
"x64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"linux"
],
"engines": {
"node": ">=18"
}
},
"node_modules/@esbuild/netbsd-arm64": {
"version": "0.24.2",
"resolved": "https://registry.npmjs.org/@esbuild/netbsd-arm64/-/netbsd-arm64-0.24.2.tgz",
"integrity": "sha512-wuLK/VztRRpMt9zyHSazyCVdCXlpHkKm34WUyinD2lzK07FAHTq0KQvZZlXikNWkDGoT6x3TD51jKQ7gMVpopw==",
"cpu": [
"arm64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"netbsd"
],
"engines": {
"node": ">=18"
}
},
"node_modules/@esbuild/netbsd-x64": {
"version": "0.24.2",
"resolved": "https://registry.npmjs.org/@esbuild/netbsd-x64/-/netbsd-x64-0.24.2.tgz",
"integrity": "sha512-VefFaQUc4FMmJuAxmIHgUmfNiLXY438XrL4GDNV1Y1H/RW3qow68xTwjZKfj/+Plp9NANmzbH5R40Meudu8mmw==",
"cpu": [
"x64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"netbsd"
],
"engines": {
"node": ">=18"
}
},
"node_modules/@esbuild/openbsd-arm64": {
"version": "0.24.2",
"resolved": "https://registry.npmjs.org/@esbuild/openbsd-arm64/-/openbsd-arm64-0.24.2.tgz",
"integrity": "sha512-YQbi46SBct6iKnszhSvdluqDmxCJA+Pu280Av9WICNwQmMxV7nLRHZfjQzwbPs3jeWnuAhE9Jy0NrnJ12Oz+0A==",
"cpu": [
"arm64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"openbsd"
],
"engines": {
"node": ">=18"
}
},
"node_modules/@esbuild/openbsd-x64": {
"version": "0.24.2",
"resolved": "https://registry.npmjs.org/@esbuild/openbsd-x64/-/openbsd-x64-0.24.2.tgz",
"integrity": "sha512-+iDS6zpNM6EnJyWv0bMGLWSWeXGN/HTaF/LXHXHwejGsVi+ooqDfMCCTerNFxEkM3wYVcExkeGXNqshc9iMaOA==",
"cpu": [
"x64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"openbsd"
],
"engines": {
"node": ">=18"
}
},
"node_modules/@esbuild/sunos-x64": {
"version": "0.24.2",
"resolved": "https://registry.npmjs.org/@esbuild/sunos-x64/-/sunos-x64-0.24.2.tgz",
"integrity": "sha512-hTdsW27jcktEvpwNHJU4ZwWFGkz2zRJUz8pvddmXPtXDzVKTTINmlmga3ZzwcuMpUvLw7JkLy9QLKyGpD2Yxig==",
"cpu": [
"x64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"sunos"
],
"engines": {
"node": ">=18"
}
},
"node_modules/@esbuild/win32-arm64": {
"version": "0.24.2",
"resolved": "https://registry.npmjs.org/@esbuild/win32-arm64/-/win32-arm64-0.24.2.tgz",
"integrity": "sha512-LihEQ2BBKVFLOC9ZItT9iFprsE9tqjDjnbulhHoFxYQtQfai7qfluVODIYxt1PgdoyQkz23+01rzwNwYfutxUQ==",
"cpu": [
"arm64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"win32"
],
"engines": {
"node": ">=18"
}
},
"node_modules/@esbuild/win32-ia32": {
"version": "0.24.2",
"resolved": "https://registry.npmjs.org/@esbuild/win32-ia32/-/win32-ia32-0.24.2.tgz",
"integrity": "sha512-q+iGUwfs8tncmFC9pcnD5IvRHAzmbwQ3GPS5/ceCyHdjXubwQWI12MKWSNSMYLJMq23/IUCvJMS76PDqXe1fxA==",
"cpu": [
"ia32"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"win32"
],
"engines": {
"node": ">=18"
}
},
"node_modules/@esbuild/win32-x64": {
"version": "0.24.2",
"resolved": "https://registry.npmjs.org/@esbuild/win32-x64/-/win32-x64-0.24.2.tgz",
"integrity": "sha512-7VTgWzgMGvup6aSqDPLiW5zHaxYJGTO4OokMjIlrCtf+VpEL+cXKtCvg723iguPYI5oaUNdS+/V7OU2gvXVWEg==",
"cpu": [
"x64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"win32"
],
"engines": {
"node": ">=18"
}
},
"node_modules/esbuild": {
"version": "0.24.2",
"resolved": "https://registry.npmjs.org/esbuild/-/esbuild-0.24.2.tgz",
"integrity": "sha512-+9egpBW8I3CD5XPe0n6BfT5fxLzxrlDzqydF3aviG+9ni1lDC/OvMHcxqEFV0+LANZG5R1bFMWfUrjVsdwxJvA==",
"dev": true,
"hasInstallScript": true,
"license": "MIT",
"bin": {
"esbuild": "bin/esbuild"
},
"engines": {
"node": ">=18"
},
"optionalDependencies": {
"@esbuild/aix-ppc64": "0.24.2",
"@esbuild/android-arm": "0.24.2",
"@esbuild/android-arm64": "0.24.2",
"@esbuild/android-x64": "0.24.2",
"@esbuild/darwin-arm64": "0.24.2",
"@esbuild/darwin-x64": "0.24.2",
"@esbuild/freebsd-arm64": "0.24.2",
"@esbuild/freebsd-x64": "0.24.2",
"@esbuild/linux-arm": "0.24.2",
"@esbuild/linux-arm64": "0.24.2",
"@esbuild/linux-ia32": "0.24.2",
"@esbuild/linux-loong64": "0.24.2",
"@esbuild/linux-mips64el": "0.24.2",
"@esbuild/linux-ppc64": "0.24.2",
"@esbuild/linux-riscv64": "0.24.2",
"@esbuild/linux-s390x": "0.24.2",
"@esbuild/linux-x64": "0.24.2",
"@esbuild/netbsd-arm64": "0.24.2",
"@esbuild/netbsd-x64": "0.24.2",
"@esbuild/openbsd-arm64": "0.24.2",
"@esbuild/openbsd-x64": "0.24.2",
"@esbuild/sunos-x64": "0.24.2",
"@esbuild/win32-arm64": "0.24.2",
"@esbuild/win32-ia32": "0.24.2",
"@esbuild/win32-x64": "0.24.2"
}
}
}
}
+5 -1
View File
@@ -4,6 +4,10 @@
"version": "1.0.0", "version": "1.0.0",
"description": "IWB 插件仓:只写插件,不复制宿主契约", "description": "IWB 插件仓:只写插件,不复制宿主契约",
"scripts": { "scripts": {
"validate": "node scripts/validate.mjs" "validate": "node scripts/validate.mjs",
"build": "node scripts/build-plugin.mjs"
},
"devDependencies": {
"esbuild": "^0.24.2"
} }
} }
+94
View File
@@ -0,0 +1,94 @@
#!/usr/bin/env node
/**
* 构建「需要打包的插件」:ESM 源码 → 单文件 IIFE 产物。
*
* 用法:node scripts/build-plugin.mjs <插件目录名> (或 npm run build -- <插件目录名>)
* 输入:<插件>/plugin/{entry.js, manifest.banner.js, manifest.footer.js, *.css}
* 输出:<插件>/<ibwPlugin.entry>(通常是 src/index.js,产物提交进仓,CI 不构建)
*
* 为什么分三段拼接,而不是把 manifest 交给 esbuild:
* 1. esbuild 的打印器会把字符串统一改写成双引号,而 scripts/validate.mjs 只认 '...' 形式;
* 2. 校验器用「文件里首个 id: '...'」判定插件 id,manifest 必须排在 bundle 之前。
* 所以 manifest 走 banner 通道(原样文本)、bundle 走 esbuild、注册调用走 footer 通道(原样文本)。
*/
import { readFileSync, existsSync } from 'node:fs'
import { resolve, dirname, join } from 'node:path'
import { fileURLToPath } from 'node:url'
const ROOT = resolve(dirname(fileURLToPath(import.meta.url)), '..')
const name = process.argv[2]
if (!name) {
console.error('用法: node scripts/build-plugin.mjs <插件目录名>')
process.exit(1)
}
const dir = join(ROOT, name)
const pkgPath = join(dir, 'package.json')
if (!existsSync(pkgPath)) {
console.error('[build] 不是插件目录(缺 package.json):' + dir)
process.exit(1)
}
let pkg
try { pkg = JSON.parse(readFileSync(pkgPath, 'utf8')) } catch (error) {
console.error('[build] package.json 解析失败:' + error.message)
process.exit(1)
}
const meta = pkg.ibwPlugin || {}
const id = String(meta.id || '')
const outFile = resolve(dir, String(meta.entry || 'src/index.js'))
const entryFile = join(dir, 'plugin', 'entry.js')
const bannerFile = join(dir, 'plugin', 'manifest.banner.js')
const footerFile = join(dir, 'plugin', 'manifest.footer.js')
for (const file of [entryFile, bannerFile, footerFile]) {
if (!existsSync(file)) {
console.error('[build] 缺少构件:' + file.replace(ROOT + '/', ''))
process.exit(1)
}
}
let esbuild
try {
esbuild = await import('esbuild')
} catch (error) {
console.error('[build] 未安装 esbuild(devDependency),请先在本仓执行:npm install')
process.exit(1)
}
// 版本只有一处真源:package.json → 注入 banner 的 __PLUGIN_VERSION__ 占位符。
const banner = readFileSync(bannerFile, 'utf8').replace(/__PLUGIN_VERSION__/g, String(pkg.version))
const footer = readFileSync(footerFile, 'utf8')
await esbuild.build({
entryPoints: [entryFile],
outfile: outFile,
bundle: true,
format: 'iife',
platform: 'browser',
target: ['chrome100', 'edge100', 'firefox100', 'safari15'],
loader: { '.css': 'text' }, // 样式以字符串内联,运行时注入 <style>(宿主 CSP 允许 unsafe-inline)
charset: 'utf8',
legalComments: 'none',
banner: { js: banner },
footer: { js: footer },
logLevel: 'warning',
})
// ===== 产物自检:宁可构建失败,也不交出会被 CI 拦下或被宿主 fail-closed 拒载的文件 =====
const out = readFileSync(outFile, 'utf8')
const fail = (message) => {
console.error('✗ ' + name + ' 产物自检失败:' + message)
process.exit(1)
}
if (!/(?:^|[\s{,])id:\s*'([^']+)'/.exec(out) || /(?:^|[\s{,])id:\s*'([^']+)'/.exec(out)[1] !== id) {
fail('首个 id 字面量不是 ' + id + '(manifest 没有排在 bundle 之前?)')
}
if (out.indexOf('IWBPluginHost.register(') < 0) fail('缺少 IWBPluginHost.register(')
if (!out.includes("version: '" + pkg.version + "'")) fail('version 与 package.json(' + pkg.version + ')不一致')
if (!/apiVersion:\s*1\b/.test(out)) fail('缺少 apiVersion: 1')
if (!/capabilities:\s*\[/.test(out)) fail('缺少 capabilities 数组')
if (/\beval\s*\(|new Function\s*\(/.test(out)) fail('含 eval/new Function,宿主 CSP(无 unsafe-eval)会拦')
console.log('✓ ' + name + ' → ' + outFile.replace(ROOT + '/', '') +
' (' + out.length + ' B, id=' + id + ', version=' + pkg.version + ')')