feat(image-annotate): 1.2.0 非破坏性裁剪(可撤销/不 flatten)+ 工具参数解耦与就地选项栏

This commit is contained in:
qiqi committed 2026-11-04 18:30:54 +08:00
1 parent a4e89f5f8b
commit d8e4e0cb26
13 files changed
+1768 -1243

No files matched your search

+17
View File
@@ -1485,3 +1485,20 @@
opacity: 0.32; cursor: not-allowed; text-decoration: line-through;
}
.iwb-editor-export-settings [data-export-key]:disabled:hover { background: #313244; }
/* 选项栏参数控件(v1.2):滑杆 + 数字框 + 实时读数,一行放得下就该保持一行 */
.iwb-opt-range {
width: 84px; height: 4px; flex: 0 0 auto;
accent-color: #4488ff; cursor: pointer;
}
.iwb-opt-val {
min-width: 32px; flex: 0 0 auto; color: #e8a735; font-size: 11px;
font-variant-numeric: tabular-nums; text-align: right;
}
.iwb-opt-unit { color: #7f849c; font-size: 11px; flex: 0 0 auto; }
/* 窄屏:参数多到放不下时横向滚动,不换行(换行会把 36px 高的选项栏撑开压画布) */
.iwb-editor-optionbar-body { overflow-x: auto; scrollbar-width: none; }
.iwb-editor-optionbar-body::-webkit-scrollbar { display: none; }
@media (max-width: 1100px) {
.iwb-opt-range { width: 64px; }
}
+83 -63
View File
@@ -1,14 +1,15 @@
/* crop.js - 裁剪工具
* 节:裁剪、裁剪栏。
* 遮罩绘制写 S.overlayCanvas,确认裁剪后重绘位图图层。
* 遮罩绘制写 S.overlayCanvas;确认裁剪后逐图层搬运像素(v1.2 起不再 flatten)。
*/
'use strict'
import { S, runtime } from './state.js'
import { getCompositeCanvas } from './tools.js'
import { setupCanvas } from './viewport.js'
import { resizeWorkspace } from './viewport.js'
import { disposeSelection } from './selection.js'
import { saveSnapshot } from './history.js'
import { toast } from './commands.js'
// ============ 裁剪 ============
@@ -235,59 +236,80 @@ import { disposeSelection } from './selection.js'
S.cropRect = { x: nx, y: ny, w: nw, h: nh }
}
/**
* 确认裁剪(v1.2 起非破坏性:可撤销、不 flatten)。
*
* 旧实现把可见图层合成成一张图再 setupCanvas,等于:① 所有图层被合并成一张;
* ② S.history 直接清零 —— 裁错了没有任何退路。现在改为:
* ① 先 saveSnapshot('裁剪'),快照记的是「裁剪前」的尺寸 + 每层像素;
* ② 逐图层把可见区域搬进新尺寸的 canvas(图层结构、命名、透明度、锁定全保留);
* ③ resizeWorkspace 只换尺寸不重建图层,像素随后写回。
* 撤销时 restoreState 会先把画布尺寸复位到快照里的 imgW/imgH,再回填像素。
*/
export function confirmCrop() {
if (!S.cropRect) return
const { x, y, w, h } = S.cropRect
if (w < 2 || h < 2) { cancelCrop(); return }
// 画布尺寸即将变化:旧坐标系下的选区/拉框/蚂蚁线/浮动条全部失效,
// 必须按 disposeSelection 级别清理,否则之后 Delete 会按旧 bbox
// 在新画布上开超大掩膜,把当前层整层擦掉。
disposeSelection()
// 合成所有可见图层
const tmp = getCompositeCanvas()
const sx = Math.round(x), sy = Math.round(y)
const sw = Math.round(w), sh = Math.round(h)
const cropC = document.createElement('canvas')
const c = S.cropConstraint
// 计算实际在原图范围内的源区域(裁剪框可超出原图边界,超出部分为透明)
const srcX = Math.max(0, sx)
const srcY = Math.max(0, sy)
const srcRight = Math.min(S.imgW, sx + sw)
const srcBottom = Math.min(S.imgH, sy + sh)
const srcW = Math.max(0, srcRight - srcX)
const srcH = Math.max(0, srcBottom - srcY)
// 在裁剪画布中的偏移
const dstX = srcX - sx
const dstY = srcY - sy
if (c.type === 'size' && c.sizeW > 0 && c.sizeH > 0) {
// 尺寸约束:先画到 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 sx = Math.round(x), sy = Math.round(y)
const sw = Math.max(1, Math.round(w)), sh = Math.max(1, Math.round(h))
const isSize = c.type === 'size' && c.sizeW > 0 && c.sizeH > 0
const scaleX = isSize ? c.sizeW / sw : 1
const scaleY = isSize ? c.sizeH / sh : 1
const nw = isSize ? Math.max(1, Math.round(c.sizeW)) : sw
const nh = isSize ? Math.max(1, Math.round(c.sizeH)) : sh
// 完全没变就别记一步空历史
if (nw === S.imgW && nh === S.imgH && sx === 0 && sy === 0) { cancelCrop(); return }
const oldW = S.imgW, oldH = S.imgH
const scaleX = nw / sw, scaleY = nh / sh
// 裁剪框可以超出画面:源矩形先夹到画面内,目标矩形按同一比例落位(超出部分为透明)
const srcX = Math.max(0, sx), srcY = Math.max(0, sy)
const srcW = Math.max(0, Math.min(oldW, sx + sw) - srcX)
const srcH = Math.max(0, Math.min(oldH, sy + sh) - srcY)
const dstX = (srcX - sx) * scaleX, dstY = (srcY - sy) * scaleY
const dstW = srcW * scaleX, dstH = srcH * scaleY
// ① 进历史:快照记「裁剪前」的尺寸与每层像素
saveSnapshot('裁剪')
// ② 旧坐标系下的选区/拉框/蚂蚁线/浮动条全部失效
disposeSelection()
// ③ 逐图层把可见区域搬出来(保留图层结构,不再合成成一张)
const staged = S.layers.map(layer => {
const tmp = document.createElement('canvas')
tmp.width = nw
tmp.height = nh
if (srcW > 0 && srcH > 0) {
try {
tmp.getContext('2d').drawImage(layer.canvas, srcX, srcY, srcW, srcH, dstX, dstY, dstW, dstH)
} catch (e) { /* 单层搬运失败不阻断其余 */ }
}
return tmp
})
// ④ 换尺寸(会清空图层像素)后把搬出来的内容写回
resizeWorkspace(nw, nh)
S.layers.forEach((layer, i) => {
const tmp = staged[i]
try { layer.ctx.drawImage(tmp, 0, 0) } catch (e) { /* ignore */ }
tmp.width = 0
tmp.height = 0
// 像素已落在新坐标系的正确位置,几何元数据不能再参与二次定位;
// 图片源(image / sourceCanvas)尺寸是旧的,留着会让重绘错位,必须摘掉。
// 摘掉后这些层按「像素层」参与快照与恢复(见 vendor/layer-logic.js)。
layer.x = 0
layer.y = 0
layer.w = nw
layer.h = nh
layer.rotation = 0
layer.transformable = false
layer.image = null
layer.sourceCanvas = null
layer._srcBox = null
layer._bounds = undefined
})
// ⑤ 文字/形状按裁剪区域位移与缩放
S.textLayers = S.textLayers.map(t => ({
...t,
x: (t.x - sx) * scaleX,
@@ -295,31 +317,29 @@ import { disposeSelection } from './selection.js'
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,
...(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
// 裁剪后 setupCanvas 会重建全部位图图层,旧 selectedLayerId 会指向已删除的 id
// 裁剪后图层 id 不变但几何全变,旧的选中 id 与拖拽中间态都要清
S.selectedLayerId = null
S.bitmapDrag = null
S.zoom = 1
setupCanvas(cropC)
S.history = []
S.redoStack = []
S.cropRect = null
S.cropHandle = null
S.cropMoving = false
S.moveStart = null
clearOverlay()
updateCropInfo()
// 尺寸/坐标系已变,统一重绘出口要在新画布上重建选区层与浮动条位置
if (S.renderAll) S.renderAll()
toast('已裁剪为 ' + nw + '×' + nh + '(Ctrl+Z 可撤销)', 'success')
}
export function cancelCrop() {
+199 -45
View File
@@ -231,14 +231,14 @@ import { hexToRgb, parseRatio, rgbToHex } from '../vendor/image-math.js'
if (!S.penPath) S.penPath = { pts: [], preview: null, closed: false }
const point = { x: clamp(pos.x, 0, S.imgW), y: clamp(pos.y, 0, S.imgH) }
const first = S.penPath.pts[0]
if (first && S.penPath.pts.length >= 3 && Math.hypot(point.x - first.x, point.y - first.y) <= Math.max(12 / S.zoom, S.brushSize * 1.5)) {
if (first && S.penPath.pts.length >= 3 && Math.hypot(point.x - first.x, point.y - first.y) <= Math.max(12 / S.zoom, S.shapeLineWidth * 1.5)) {
S.penPath.closed = true
S.penPath.nearStart = true
S.penPath.preview = null
commitPenPath()
} else {
S.penPath.pts.push(point)
renderObjects({ id: 'pen-preview', type: 'pen', pts: S.penPath.pts.concat(S.penPath.preview ? [S.penPath.preview] : []), closed: false, color: S.color, lw: Math.max(2, S.brushSize), fill: false, opacity: 1, visible: true })
renderObjects({ id: 'pen-preview', type: 'pen', pts: S.penPath.pts.concat(S.penPath.preview ? [S.penPath.preview] : []), closed: false, color: S.color, lw: Math.max(1, S.shapeLineWidth), fill: false, opacity: 1, visible: true })
}
return
}
@@ -423,7 +423,7 @@ import { hexToRgb, parseRatio, rgbToHex } from '../vendor/image-math.js'
/** 钢笔路径预览:更新悬停点与起点闭合提示 */
function onPenDrawMove(pos) {
if (S.penPath) { S.penPath.preview = pos; const first = S.penPath.pts[0]
const nearStart = first && S.penPath.pts.length >= 3 && Math.hypot(pos.x - first.x, pos.y - first.y) <= Math.max(12 / S.zoom, S.brushSize * 1.5)
const nearStart = first && S.penPath.pts.length >= 3 && Math.hypot(pos.x - first.x, pos.y - first.y) <= Math.max(12 / S.zoom, S.shapeLineWidth * 1.5)
S.penPath.nearStart = !!nearStart
renderObjects() }
}
@@ -436,8 +436,8 @@ import { hexToRgb, parseRatio, rgbToHex } from '../vendor/image-math.js'
x1: S.startX, y1: S.startY,
x2: pos.x, y2: pos.y,
color: S.color,
lw: Math.max(2, S.brushSize),
lineWidth: Math.max(2, S.brushSize),
lw: Math.max(1, S.shapeLineWidth),
lineWidth: Math.max(1, S.shapeLineWidth),
fill: S.tool === 'rect' || S.tool === 'circle' ? !!S.rectFill : false,
opacity: 1,
visible: true
@@ -635,7 +635,7 @@ import { hexToRgb, parseRatio, rgbToHex } from '../vendor/image-math.js'
x1: S.startX, y1: S.startY,
x2: pos.x, y2: pos.y,
color: S.color,
lw: Math.max(2, S.brushSize),
lw: Math.max(1, S.shapeLineWidth),
fill: S.tool === 'rect' || S.tool === 'circle' ? !!S.rectFill : false,
opacity: 1,
visible: true,
@@ -799,32 +799,101 @@ import { hexToRgb, parseRatio, rgbToHex } from '../vendor/image-math.js'
picker: '吸管', hand: '抓手', crop: '裁剪'
}
/** 选项栏只露当前工具 2–3 个参数;用独立控件,避免与右侧旧参数区抢 querySelector */
export function renderOptionBar() {
const body = runtime.el && runtime.el.querySelector('.iwb-editor-optionbar-body')
if (!body) return
let html = ''
if (S.tool === 'marquee') {
html = `<span class="iwb-opt-label">形状</span>
const OPT_HINTS = {
crop: '裁剪栏在画布下方;裁剪与选区互斥,确认后可 Ctrl+Z 撤销',
select: '点击选中元素,拖拽移动,手柄缩放',
picker: '点击画布取色,取完自动切回上一个工具',
hand: '拖拽平移画布;任意工具下按住空格也可以',
marquee: '拖出选区 → 操作条就在选区旁边',
lasso: '按住拖动画圈,松手闭合'
}
/** 滑杆 + 数字框共用同一 data-opt,两条输入路径都写回 S */
function rangeOpt(key, label, min, max, value, unit) {
return `<span class="iwb-opt-label">${label}</span>
<input type="range" class="iwb-opt-range" data-opt="${key}" min="${min}" max="${max}" step="1" value="${value}">
<input type="number" class="iwb-opt-num" data-opt="${key}" min="${min}" max="${max}" step="1" value="${value}">${unit ? `<span class="iwb-opt-unit">${unit}</span>` : ''}`
}
/** 每个工具只露最常用的 2–4 个参数,全部直接写回 S(右侧参数面板同步) */
function optionBarHTML(tool) {
if (tool === 'brush' || tool === 'eraser') {
return rangeOpt('brushSize', '大小', 1, 300, S.brushSize, '')
+ `<span class="iwb-opt-label">硬度</span>
<input type="range" class="iwb-opt-range" data-opt="brushHardness" min="0" max="100" step="1" value="${S.brushHardness}">
<span class="iwb-opt-val" data-opt-val="brushHardness">${S.brushHardness}</span>
<span class="iwb-opt-label">透明</span>
<input type="range" class="iwb-opt-range" data-opt="brushOpacity" min="5" max="100" step="1" value="${Math.round(S.brushOpacity * 100)}">
<span class="iwb-opt-val" data-opt-val="brushOpacity">${Math.round(S.brushOpacity * 100)}%</span>`
}
if (tool === 'rect' || tool === 'circle') {
return rangeOpt('shapeLineWidth', '线宽', 1, 60, S.shapeLineWidth, '')
+ `<span class="iwb-opt-label">样式</span>
<button class="iwb-opt-btn${S.rectFill ? '' : ' active'}" data-opt-toggle="stroke" data-value="stroke">描边</button>
<button class="iwb-opt-btn${S.rectFill ? ' active' : ''}" data-opt-toggle="fill" data-value="fill">实心</button>`
}
if (tool === 'arrow' || tool === 'pen') {
return rangeOpt('shapeLineWidth', '线宽', 1, 60, S.shapeLineWidth, '')
+ `<span class="iwb-opt-hint">${tool === 'pen' ? '逐点点击,点回起点闭合' : '拖出箭头,松手完成'}</span>`
}
if (tool === 'text') {
return rangeOpt('textSize', '字号', 8, 400, S.textSize, 'px')
+ '<span class="iwb-opt-hint">点画布输入文字,Enter 确认</span>'
}
if (tool === 'marquee') {
return `<span class="iwb-opt-label">形状</span>
<button class="iwb-opt-btn${S.selectionKind === 'rect' ? ' active' : ''}" data-opt="shape" data-value="rect">矩形</button>
<button class="iwb-opt-btn${S.selectionKind === 'ellipse' ? ' active' : ''}" data-opt="shape" data-value="ellipse">椭圆</button>
<label class="iwb-opt-label">羽化 <input type="number" class="iwb-opt-num" data-opt="feather" min="0" max="20" step="1" value="${S.selectionFeather}"> px</label>
<span class="iwb-opt-hint">拖出选区 → 操作条就在选区旁边</span>`
} else if (S.tool === 'lasso') {
html = `<span class="iwb-opt-label">套索</span>
<label class="iwb-opt-label">羽化 <input type="number" class="iwb-opt-num" data-opt="feather" min="0" max="20" step="1" value="${S.selectionFeather}"> px</label>
<span class="iwb-opt-hint">按住拖动画圈,松手闭合</span>`
} else {
const hints = {
crop: '裁剪栏在画布下方;裁剪与选区互斥',
brush: '选区激活时笔刷只画在选区内',
eraser: '橡皮只擦当前画笔目标图层(✎)',
select: '点击选中元素,拖拽移动,手柄缩放'
}
html = `<span class="iwb-opt-current">当前工具:${TOOL_NAMES[S.tool] || S.tool}</span>
<span class="iwb-opt-hint">${hints[S.tool] || '选区工具按 M / L;Ctrl+J 复制选区,Delete 清除当前层'}</span>`
<span class="iwb-opt-hint">${OPT_HINTS.marquee}</span>`
}
body.innerHTML = html
if (tool === 'lasso') {
return `<span class="iwb-opt-label">羽化 <input type="number" class="iwb-opt-num" data-opt="feather" min="0" max="20" step="1" value="${S.selectionFeather}"> px</span>
<span class="iwb-opt-hint">${OPT_HINTS.lasso}</span>`
}
return `<span class="iwb-opt-current">当前工具:${TOOL_NAMES[tool] || tool}</span>
<span class="iwb-opt-hint">${OPT_HINTS[tool] || '选区工具按 M / L;Ctrl+J 复制选区,Delete 清除当前层'}</span>`
}
export function renderOptionBar(force) {
const body = runtime.el && runtime.el.querySelector('.iwb-editor-optionbar-body')
if (!body) return
// 工具没变就只同步数值:renderAll 每次操作都会走到这里,全量重建 innerHTML
// 会打断正在拖的滑杆和正在输入的数字框(静态审查 P2-11)。
if (!force && body.dataset.tool === S.tool) { syncOptionBar(); return }
body.dataset.tool = S.tool
body.innerHTML = optionBarHTML(S.tool)
syncOptionBar()
}
/** 只更新值与选中态,不重建 DOM —— 保证拖拽中的控件与输入焦点不被抢 */
export function syncOptionBar() {
const body = runtime.el && runtime.el.querySelector('.iwb-editor-optionbar-body')
if (!body) return
const val = (key) => {
if (key === 'brushSize') return S.brushSize
if (key === 'brushHardness') return S.brushHardness
if (key === 'brushOpacity') return Math.round(S.brushOpacity * 100)
if (key === 'shapeLineWidth') return S.shapeLineWidth
if (key === 'textSize') return S.textSize
if (key === 'feather') return S.selectionFeather
return ''
}
body.querySelectorAll('input[data-opt]').forEach(el => {
if (document.activeElement === el) return // 正在拖/正在输入的不要被覆盖
const v = val(el.dataset.opt)
if (String(el.value) !== String(v)) el.value = v
})
body.querySelectorAll('[data-opt-val]').forEach(el => {
const v = val(el.dataset.optVal)
el.textContent = el.dataset.optVal === 'brushOpacity' ? v + '%' : v
})
body.querySelectorAll('[data-opt="shape"]').forEach(btn => {
btn.classList.toggle('active', S.selectionKind === btn.dataset.value)
})
body.querySelectorAll('[data-opt-toggle]').forEach(btn => {
btn.classList.toggle('active', !!S.rectFill === (btn.dataset.value === 'fill'))
})
}
/** 状态栏:缩放 / 尺寸 / 光标 / 选区 / 当前层 / 工具 */
@@ -847,6 +916,74 @@ import { hexToRgb, parseRatio, rgbToHex } from '../vendor/image-math.js'
put('.iwb-editor-status-tool', TOOL_NAMES[S.tool] || S.tool)
}
// ---- 选项栏参数写回:单一真源是 S,右侧参数面板与画布随后同步 ----
let lwSnapDone = false
let textSnapDone = false
/** 线宽也作用到当前选中的形状:拖动中只重绘,松手才记一步历史 */
function applyShapeLineWidth(committed) {
const sh = getSelectedShape()
if (!sh || sh.locked) { lwSnapDone = false; return }
if (committed || !lwSnapDone) { saveSnapshot('线宽'); lwSnapDone = true }
sh.lw = S.shapeLineWidth
renderObjects()
if (committed) lwSnapDone = false
}
/** 字号也作用到当前选中的文字 */
function applyTextSize(committed) {
const t = getSelectedText()
if (!t || t.locked) { textSnapDone = false; return }
if (committed || !textSnapDone) { saveSnapshot('字号'); textSnapDone = true }
t.fontSize = S.textSize
renderObjects()
if (committed) textSnapDone = false
}
/** 形状描边/实心:既改下次新建的默认值,也改当前选中的那个 */
function setShapeFill(fill) {
S.rectFill = !!fill
updateFillUI()
syncOptionBar()
const sh = getSelectedShape()
if (sh && (sh.type === 'rect' || sh.type === 'circle') && !sh.locked) {
saveSnapshot('填充')
sh.fill = S.rectFill
renderObjects()
}
}
function setOptionFromControl(el, committed) {
const key = el && el.dataset ? el.dataset.opt : ''
if (!key) return
const n = Math.round(Number(el.value))
const safe = Number.isFinite(n) ? n : 0
if (key === 'brushSize') {
S.brushSize = clamp(safe || 1, 1, 300)
updateBrushUI()
updateBrushParamUI()
} else if (key === 'brushHardness') {
S.brushHardness = clamp(safe, 0, 100)
updateBrushParamUI()
} else if (key === 'brushOpacity') {
S.brushOpacity = clamp(safe || 100, 5, 100) / 100
updateBrushParamUI()
if (S.strokeCanvas) S.strokeCanvas.style.opacity = S.brushOpacity
} else if (key === 'shapeLineWidth') {
S.shapeLineWidth = clamp(safe || 1, 1, 60)
applyShapeLineWidth(committed)
} else if (key === 'textSize') {
S.textSize = clamp(safe || 32, 8, 400)
applyTextSize(committed)
} else if (key === 'feather') {
S.selectionFeather = clamp(safe, 0, 20)
if (S.selection && S.selection.active) S.selection.feather = S.selectionFeather
updateStatusbar()
}
syncOptionBar()
}
/** 更多菜单 / 面板收起 / 选项栏控件:只绑定一次,DOM 重绘不丢事件(委托) */
export function bindLiteUI() {
const root = runtime.el
@@ -907,23 +1044,25 @@ import { hexToRgb, parseRatio, rgbToHex } from '../vendor/image-math.js'
const body = root.querySelector('.iwb-editor-optionbar-body')
if (body) {
body.addEventListener('mousedown', (e) => e.stopPropagation())
// 滑杆拖动中(input)与松手/失焦(change)走同一条写回路径,
// committed 只决定「要不要顺手记一步历史」,不影响参数生效。
body.addEventListener('input', (e) => setOptionFromControl(e.target, false))
body.addEventListener('change', (e) => setOptionFromControl(e.target, true))
body.addEventListener('click', (e) => {
const btn = e.target.closest('[data-opt="shape"]')
if (!btn) return
e.stopPropagation()
S.selectionKind = btn.dataset.value === 'ellipse' ? 'ellipse' : 'rect'
renderOptionBar()
toast('选区形状:' + (S.selectionKind === 'ellipse' ? '椭圆' : '矩形'), 'info')
const shapeBtn = e.target.closest('[data-opt="shape"]')
if (shapeBtn) {
e.stopPropagation()
S.selectionKind = shapeBtn.dataset.value === 'ellipse' ? 'ellipse' : 'rect'
syncOptionBar()
toast('选区形状:' + (S.selectionKind === 'ellipse' ? '椭圆' : '矩形'), 'info')
return
}
const toggle = e.target.closest('[data-opt-toggle]')
if (toggle) {
e.stopPropagation()
setShapeFill(toggle.dataset.value === 'fill')
}
})
const onFeather = (e) => {
const input = e.target.closest('[data-opt="feather"]')
if (!input) return
S.selectionFeather = clamp(parseInt(input.value, 10) || 0, 0, 20)
if (S.selection && S.selection.active) S.selection.feather = S.selectionFeather
updateStatusbar()
}
body.addEventListener('input', onFeather)
body.addEventListener('change', onFeather)
}
// 点画布 / 面板其它地方收起下拉。必须用捕获阶段:modal 自身有个
@@ -1277,7 +1416,7 @@ import { hexToRgb, parseRatio, rgbToHex } from '../vendor/image-math.js'
function commitPenPath() {
if (!S.penPath || S.penPath.pts.length < 2) { S.penPath = null; renderObjects(); return }
saveSnapshot()
const shape = { id: 's' + Date.now() + Math.floor(Math.random() * 1000), type: 'pen', pts: S.penPath.pts.slice(), closed: !!S.penPath.closed, color: S.color, lw: Math.max(2, S.brushSize), fill: !!S.penPath.closed, opacity: 1, visible: true, locked: false, z: ++S.zCounter }
const shape = { id: 's' + Date.now() + Math.floor(Math.random() * 1000), type: 'pen', pts: S.penPath.pts.slice(), closed: !!S.penPath.closed, color: S.color, lw: Math.max(1, S.shapeLineWidth), fill: !!S.penPath.closed, opacity: 1, visible: true, locked: false, z: ++S.zCounter }
S.shapeLayers.push(shape); selectUnit('shape', shape.id); S.penPath = null; renderObjects(); renderLayerPanel()
}
@@ -1452,9 +1591,24 @@ import { hexToRgb, parseRatio, rgbToHex } from '../vendor/image-math.js'
S.drawCanvasCursor('crosshair')
}
/**
* 是否处于「正在输入文字」态 —— 只对**文字内容**输入框为真。
*
* v1.2 修正:原来任何 INPUT 都算打字,于是在选项栏的数字框(羽化/线宽/字号)
* 里输完值后,Ctrl+A、Ctrl+J、Delete、Esc 全被吞掉,表现成「快捷键突然没反应」。
* 参数控件里带修饰键的组合、Delete 与 Esc 一律放行给画布;单个字符仍然正常输入。
*/
function isTyping(e) {
const t = e.target
return t && (t.tagName === 'INPUT' || t.tagName === 'TEXTAREA')
if (!t) return false
if (t.tagName === 'TEXTAREA') return true
if (t.tagName !== 'INPUT') return false
const cls = t.classList
if (cls && (cls.contains('iwb-editor-text-input') || cls.contains('iwb-editor-color-hex-input'))) return true
// 以下是参数控件(数字框 / 滑杆)
if (e.ctrlKey || e.metaKey || e.altKey) return false
if (e.key === 'Delete' || e.key === 'Escape') return false
return true
}
function onKeydown(e) {
+13 -1
View File
@@ -17,7 +17,7 @@ import {
createLayerCanvas, purgeVectorCanvases, redrawBitmapLayer,
renderLayerPanel, reorderLayerCanvas, updateLayerCanvasStyles
} from './layers.js'
import { setupCanvas } from './viewport.js'
import { resizeWorkspace, setupCanvas } from './viewport.js'
import { updateAllUI } from './events.js'
import { isDrawableLayer, needsPixelSnapshot, restorePath } from '../vendor/layer-logic.js'
import { toast } from './commands.js'
@@ -160,6 +160,18 @@ import { toast } from './commands.js'
/** 恢复到指定状态(含图层增删) */
function restoreState(state) {
// v1.2:裁剪也进历史链,所以快照的画布尺寸可能与当前不同,必须先把尺寸复位。
// 尺寸一变,现有图层对象的像素缓冲已被 resizeWorkspace 清空、几何元数据也失效,
// 直接「复用现有图层再 putImageData」会让走过 redraw 路径的图片层彻底丢内容;
// 因此全部释放、让下面的「按快照重建」分支统一重建(它会按 bm 的 imageRef/sourceRef
// 选择 redraw 还是 pixels)。
if (state.imgW && state.imgH && (state.imgW !== S.imgW || state.imgH !== S.imgH)) {
purgeVectorCanvases()
for (const l of S.layers) releaseLayer(l)
S.layers = []
resizeWorkspace(state.imgW, state.imgH)
}
purgeVectorCanvases()
for (const l of S.layers) l._bounds = undefined
+11 -1
View File
@@ -95,6 +95,8 @@ import { toast } from './commands.js'
S.prevTool = null
S.pickerComposite = null
S.rectFill = false
S.shapeLineWidth = 3
S.textSize = 32
S.cropConstraint = { type: 'free', ratio: 0, sizeW: 0, sizeH: 0 }
S.textLayers = []
S.selectedTextId = null
@@ -284,12 +286,20 @@ import { toast } from './commands.js'
tool: S.tool,
doc: { w: S.imgW, h: S.imgH },
layers: S.layers.map(l => ({ id: l.id, name: l.name, z: l.z, locked: !!l.locked, visible: l.visible !== false })),
shapes: S.shapeLayers.map(s => ({ id: s.id, type: s.type })),
shapes: S.shapeLayers.map(s => ({ id: s.id, type: s.type, lw: s.lw, fill: !!s.fill })),
texts: S.textLayers.map(t => ({ id: t.id, text: t.text })),
selectedShapeId: S.selectedShapeId,
selectedTextId: S.selectedTextId,
activeLayerId: S.activeLayerId,
selection: selectionInfo(),
toolOptions: {
brushSize: S.brushSize,
brushHardness: S.brushHardness,
brushOpacity: S.brushOpacity,
shapeLineWidth: S.shapeLineWidth,
textSize: S.textSize,
rectFill: S.rectFill
},
history: S.history.length,
historyLabels: S.history.map(s => s.__label || ''),
redo: S.redoStack.length,
+3 -3
View File
@@ -343,12 +343,12 @@ import { isDrawableLayer } from '../vendor/layer-logic.js'
const ctx = S.overlayCtx
const pts = path.pts.slice()
const first = pts[0]
const nearStart = path.preview && pts.length >= 3 && Math.hypot(path.preview.x - first.x, path.preview.y - first.y) <= Math.max(12 / S.zoom, S.brushSize * 1.5)
const nearStart = path.preview && pts.length >= 3 && Math.hypot(path.preview.x - first.x, path.preview.y - first.y) <= Math.max(12 / S.zoom, S.shapeLineWidth * 1.5)
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.lineWidth = Math.max(1, S.shapeLineWidth) / S.zoom
ctx.setLineDash([8 / S.zoom, 5 / S.zoom])
ctx.beginPath()
ctx.moveTo(pts[0].x, pts[0].y)
@@ -604,7 +604,7 @@ import { isDrawableLayer } from '../vendor/layer-logic.js'
id: 't' + Date.now() + Math.floor(Math.random() * 1000),
x, y, text,
color: S.color,
fontSize: Math.max(16, S.brushSize * 6),
fontSize: Math.max(8, S.textSize),
opacity: 1,
visible: true,
locked: false,
+5 -1
View File
@@ -21,7 +21,11 @@
brushOpacity: 1, // 画笔透明度 0.05~1(一笔整体透明度,笔划内不叠加)
prevTool: null, // 吸管工具激活前的工具(取色后切回)
pickerComposite: null, // 吸管取样用的合成画布缓存(切工具/画布变化时失效)
rectFill: false, // 矩形是否实心填充
rectFill: false, // 矩形/圆形是否实心填充
// v1.2 工具参数解耦:形状线宽与文字字号不再借用画笔粗细,
// 否则「调细画笔」会顺手把所有形状的描边一起改掉。
shapeLineWidth: 3, // 矩形/圆形/箭头/钢笔的描边粗细
textSize: 32, // 新建文字的字号 px
// 图层系统
layers: [], // 位图图层数组 [{ id, name, canvas, ctx, opacity, visible, z }]
activeLayerId: null, // 当前活跃位图图层 ID(画笔/橡皮操作目标)
+42
View File
@@ -105,6 +105,48 @@ import { getSelectedShape, getSelectedText, renderObjects, shapeBounds, textBoun
bindCanvasEvents()
}
/**
* 只调整画布尺寸与交互层,不重建图层(裁剪 / 撤销裁剪共用)。
*
* 与 setupCanvas 的分工:setupCanvas 会清空 S.layers 并新建「原图 + 画笔」两层,
* 那是「打开一张新图」的语义。裁剪只是在同一张图上换视窗,像素由调用方先搬好,
* 这里只负责尺寸、交互层、矢量层与视图基准,图层结构原样保留。
*
* ⚠️ 这里会把每个图层 canvas 的像素缓冲清空(canvas.width 赋值即重置),
* 调用方必须在调用前把像素复制出来,调用后写回。
*/
export function resizeWorkspace(w, h) {
S.imgW = Math.max(1, Math.round(w))
S.imgH = Math.max(1, Math.round(h))
S.textCanvas.width = S.imgW
S.textCanvas.height = S.imgH
S.strokeCanvas.width = S.imgW
S.strokeCanvas.height = S.imgH
S.overlayPad = Math.max(96, Math.ceil(Math.max(S.imgW, S.imgH) * 0.18))
for (const [c, cx] of [[S.overlayCanvas, S.overlayCtx], [S.selectionCanvas, S.selectionCtx], [S.cursorCanvas, S.cursorCtx]]) {
if (!c || !cx) continue
c.width = S.imgW + S.overlayPad * 2
c.height = S.imgH + S.overlayPad * 2
cx.setTransform(1, 0, 0, 1, S.overlayPad, S.overlayPad)
}
purgeVectorCanvases()
for (const layer of S.layers) {
layer.canvas.width = S.imgW
layer.canvas.height = S.imgH
layer._bounds = undefined
}
S.pickerComposite = null
clearOverlay()
computeFit()
S.viewX = null
applyView()
renderObjects()
renderLayerPanel()
}
/** 计算「适应容器」的基准显示尺寸(不限制放大,小图也铺满) */
function computeFit() {
const availW = Math.max(50, S.canvasWrap.clientWidth - 48)