Files
iwb-plugins-desktop/image-annotate/plugin/editor/tools.js
T
qiqi 3e76f2792e feat(image-annotate): v1.7.0 图层面板补齐(缩略图 / 重命名 / 不透明度)
按通读代码后定的顺序处理 P3 剩余项里最有价值的三条。

1) 不透明度真正可调
   opacity 字段一直在(合成/合并/导出/快照都读它),但面板没有任何控件能写它,
   roadmap 里标的「已有」与事实不符。现在选中层后在该项下方展开滑杆:
   - 位图走 canvas 的 CSS opacity(像素不动),导出/合并时乘 globalAlpha,所见即所得
   - 文字/形状改完重绘矢量层(不透明度已烘进像素,不能再叠 CSS)
   - input 第一次到达才拍快照,一次拖动只产生 1 条历史;双击滑杆复位 100%
   - 非 100% 且未选中的层在名字旁挂百分比角标

2) 缩略图 + 双击重命名
   - 22px 缩略图(canvas 44 设备像素),等比缩放居中;空图层透出类型图标兜底
   - 绘制合批 90ms,避免每次 renderLayerPanel 都重画几十张
   - 双击名字改名(Enter 提交 / Esc 放弃),改名期间禁用整项拖动

3) 顺手清理
   - 删除 .iwb-layer-color / .iwb-layer-width 两个永远看不见的死控件
     (CSS display:none !important 写了三遍),连同绑定与死样式
   - pasteImageFromUrl 的 window.alert 改 toast(阻塞弹窗在宿主里会卡整页)
   - resetState() 补清 layerMulti / hoverPos / lastClick / lastNameClick / altPicker

关键修正:矢量层不透明度只能乘一次。
drawVectorToCanvas / drawShape 已把 opacity 画进像素,getCompositeCanvas 与
composeUnitsInto 再乘 globalAlpha 就是双倍透明 —— 两处都改为只对位图乘。

验证:harness 133 项全通(新增 4 项)、validate 9/9、产物 331811 B。
harness 的版本断言改为读 package.json,不再硬编码。
2026-11-08 16:43:38 +08:00

448 lines
17 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
/* tools.js - 画笔、橡皮、吸管与合成画布
* 节:绘制工具、合成画布(吸管取样 / 导出 / 裁剪共用)。
* 约定:brushStampCache 是模块级缓存,只在本模块内重建;
* getCompositeCanvas 把所有可见图层+矢量对象合成到一张画布,
* 吸管/导出/裁剪共用它。
*/
'use strict'
import { S, runtime } from './state.js'
import { commitTextInput, getSelectedShape, getSelectedText, layerUnits, 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()
if (S.selection && S.selection.active) ctx.clip(S.selection.path, S.selection.fillRule)
ctx.globalCompositeOperation = 'destination-out'
ctx.globalAlpha = S.brushOpacity
ctx.lineWidth = Math.max(1, S.brushSize)
ctx.lineCap = 'round'
ctx.lineJoin = 'round'
ctx.beginPath()
ctx.moveTo(x1, y1)
ctx.lineTo(x2, y2)
ctx.stroke()
ctx.restore()
const active = getActiveLayer()
if (active && active.id === 'draw' && active.sourceCanvas) {
const sourceCtx = active.sourceCanvas.getContext('2d', { willReadFrequently: true })
sourceCtx.save()
sourceCtx.globalCompositeOperation = 'destination-out'
sourceCtx.globalAlpha = S.brushOpacity
sourceCtx.lineWidth = Math.max(1, S.brushSize) * active.w / Math.max(S.imgW, 1)
sourceCtx.lineCap = 'round'
sourceCtx.beginPath()
sourceCtx.moveTo((x1 - active.x) * S.imgW / active.w, (y1 - active.y) * S.imgW / active.w)
sourceCtx.lineTo((x2 - active.x) * S.imgW / active.w, (y2 - active.y) * S.imgW / active.w)
sourceCtx.stroke()
sourceCtx.restore()
}
S.pickerComposite = null
renderObjects()
}
/** 开始一笔 */
/** 若绘制层已被变换(移动/缩放/旋转),先把结果固化并重置变换参数,保证继续绘制的坐标正确 */
function bakeDrawableLayer(layer) {
if (!layer || !isDrawableLayer(layer) || !layer._srcBox) return
layer._srcBox = null
layer.sourceCanvas = null
layer.rotation = 0
layer.x = 0
layer.y = 0
layer.w = S.imgW
layer.h = S.imgH
layer._bounds = 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.selection && S.selection.active) ctx.clip(S.selection.path, S.selection.fillRule)
if (S.tool === 'eraser') {
ctx.globalCompositeOperation = 'destination-out'
}
ctx.globalAlpha = S.brushOpacity
ctx.drawImage(S.strokeCanvas, 0, 0)
ctx.restore()
S.strokeCanvas.style.display = 'none'
const active = getActiveLayer()
if (active && active.id === 'draw' && active.sourceCanvas && active.w > 0 && active.h > 0) {
const sourceCtx = active.sourceCanvas.getContext('2d', { willReadFrequently: true })
sourceCtx.save()
sourceCtx.globalCompositeOperation = S.tool === 'eraser' ? 'destination-out' : 'source-over'
sourceCtx.globalAlpha = S.brushOpacity
sourceCtx.translate(-active.x * S.imgW / active.w, -active.y * S.imgH / active.h)
sourceCtx.scale(S.imgW / active.w, S.imgH / active.h)
sourceCtx.drawImage(S.strokeCanvas, 0, 0)
sourceCtx.restore()
}
S.strokeCtx.clearRect(0, 0, S.imgW, S.imgH)
S.pickerComposite = null
}
/** 按形状对象绘制(矩形/箭头),预览与最终渲染共用 */
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 clearToolRing() {
const ctx = S.cursorCtx
if (!ctx) return
const pad = S.overlayPad || 0
ctx.save()
ctx.setTransform(1, 0, 0, 1, 0, 0)
ctx.clearRect(0, 0, S.imgW + pad * 2, S.imgH + pad * 2)
ctx.restore()
ctx.setTransform(1, 0, 0, 1, pad, pad)
}
/** 圆形笔刷光标:画在独立 cursorCanvas,避免 clearOverlay() 擦掉其它交互层 */
export function drawToolRing(pos) {
clearToolRing()
const ctx = S.cursorCtx || S.overlayCtx
const r = getToolBrushRadius()
const k = 1 / screenScale()
const rMin = 2 * k
const rr = Math.max(r, rMin)
ctx.save()
ctx.lineWidth = k
ctx.strokeStyle = 'rgba(0,0,0,0.8)'
ctx.beginPath()
ctx.arc(pos.x, pos.y, rr, 0, Math.PI * 2)
ctx.stroke()
ctx.strokeStyle = 'rgba(255,255,255,0.9)'
ctx.lineWidth = k
ctx.beginPath()
ctx.arc(pos.x, pos.y, Math.max(rr - k, 0), 0, Math.PI * 2)
ctx.stroke()
ctx.restore()
}
// ============ 合成画布(吸管取样 / 导出 / 裁剪共用) ============
/** 合成所有可见图层到一个临时 canvas */
export function getCompositeCanvas() {
const c = document.createElement('canvas')
c.width = S.imgW
c.height = S.imgH
const cx = c.getContext('2d', { willReadFrequently: true })
// 与 DOM 叠放 / 图层面板 / 命中测试共用同一份 z 序(唯一真源)
cx.globalAlpha = 1
for (const u of layerUnits()) {
if (u.obj.visible === false) continue
const el = u.kind === 'bitmap' ? u.obj.canvas : u.obj._canvas
if (!el) continue
// 位图的 opacity 由 CSS 显示、这里乘 alpha;矢量对象的不透明度已经画进像素
cx.globalAlpha = u.kind === 'bitmap' ? (u.obj.opacity == null ? 1 : u.obj.opacity) : 1
cx.drawImage(el, 0, 0)
}
cx.globalAlpha = 1
return c
}
/** 吸管取样用的合成画布缓存 */
function getPickerComposite() {
if (!S.pickerComposite) {
S.pickerComposite = getCompositeCanvas().getContext('2d', { willReadFrequently: true })
}
return S.pickerComposite
}
/** 取画布坐标处的合成像素颜色 */
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() {
// 按住 Alt 的临时吸管:取色后不退出(PS 手感:Alt 按住期间可连续吸色),
// 由 keyup / 窗口失焦时的 endAltPicker() 统一收尾回到原工具
if (S.altPicker) {
S.pickerComposite = null
hidePickerTip()
return
}
S.tool = (S.prevTool && S.prevTool !== 'picker') ? S.prevTool : 'brush'
S.prevTool = null
// 回到的若不是选择/形状类工具,选中态按 setTool 同一套规则清掉,避免画布残留选中框
const back = S.tool
// 与 setTool 同一套规则(v1.3):只有选择工具保留选中态
if (back !== 'select') {
S.selectedLayerId = null
S.selectedTextId = null
S.selectedShapeId = null
}
S.pickerComposite = null
hidePickerTip()
updateToolUI()
updateBrushParamUI()
if (S.tool === 'crop') {
showCropBar()
updateCropInfo()
} else {
cancelCrop()
hideCropBar()
}
// 回到上一个工具后选项栏由 updateToolUI() → renderOptionBar() 按新工具重建
renderObjects()
}
/**
* PS 手感:画笔 / 橡皮下按住 Alt 临时变成吸管,松开 Alt 回到原工具。
* 只在这两个绘制工具下生效;正在描笔时(isDrawing)不打断。
* 取色后不退出吸管(见 exitPicker 的 altPicker 分支),可以按住 Alt 连续吸色。
*/
export function beginAltPicker() {
if (S.altPicker) return
if (S.tool !== 'brush' && S.tool !== 'eraser') return
if (S.isDrawing) return
S.altPicker = true
setTool('picker') // setTool 会把原工具存进 prevTool,松开 Alt 时用它还原
}
/** 松开 Alt / 窗口失焦:结束临时吸管并回到原工具 */
export function endAltPicker() {
if (!S.altPicker) return
S.altPicker = false
exitPicker()
}
/** 统一颜色应用:设置当前色 + 同步选中文字/形状颜色。
* opts.skipHistory:连续取色(拖 SV/色相条)时由调用方在拖动开始时已拍过快照,
* 这里不再逐步 saveSnapshot —— 否则拖一下就是几百张全画质 ImageData。 */
export function applyColorChange(color, opts) {
const skipHistory = !!(opts && opts.skipHistory)
S.color = color
updateColorUI()
const t = getSelectedText()
if (t && !t.locked && t.color !== S.color) {
if (!skipHistory) saveSnapshot()
t.color = S.color
renderObjects()
}
const sh = getSelectedShape()
if (sh && !sh.locked && S.tool !== 'text' && sh.color !== S.color) {
if (!skipHistory) saveSnapshot()
sh.color = S.color
renderObjects()
}
}
/** 切换工具(工具栏按钮、快捷键、调色板吸色共用)。保留同类形状选中以便继续编辑。 */
export function setTool(tool) {
if (S.placingImage) cancelImagePlacement()
commitTextInput()
// 用户主动切到别的工具 = 放弃「按住 Alt 临时吸管」,否则松 Alt 会把工具抢回去
if (tool !== 'picker') S.altPicker = false
// 钢笔节点编辑与文字编辑都只属于 V(v1.5):切到任何创建类工具都退出编辑态,
// 否则从 V 带着 penEditId 切到 P 会出现「钢笔下能拖节点但点不动」的半状态。
if (tool !== 'select') { S.penEditId = null; S.penDragPt = -1; S.penDragPending = null }
if (tool === 'picker' && S.tool !== 'picker') S.prevTool = S.tool
if (tool !== 'pen') S.penPath = null
// 选区与裁剪互斥:进裁剪必须清掉选区;离开选区工具要丢弃未完成的拉框/套索
if (tool === 'crop') { S.selection = null; S.marquee = null; S.lassoPts = null }
if (tool !== 'marquee' && tool !== 'lasso') {
if (S.marquee || S.lassoPts) { S.isDrawing = false; S.interaction = 'idle' }
S.marquee = null
S.lassoPts = null
}
S.tool = tool
// 吸管是临时取色工具:必须保留选中态,否则「选中形状 → 按 I 取色」时选中被清掉,
// applyColorChange 找不到对象,颜色只写进画笔色、形状不变(用户反馈 2026-11-04)
// 选中态只属于「选择(V)」与临时吸管(v1.3,用户裁定 2026-11-05):
// 矩形/圆形/箭头/钢笔/文字都只负责新建,切过去就清掉选中 ——
// 否则矢量工具下点到已有图形会被当成拖动它,没法在它上面继续画。
const keepSel = tool === 'select' || tool === 'picker'
if (!keepSel) {
S.selectedLayerId = null
S.selectedTextId = null
S.selectedShapeId = null
}
S.bitmapDrag = null
S.textDrag = null
S.shapeDrag = null
S.pickerComposite = null
S.lastClick = null // 切工具即断掉双击序列,避免拿上一个工具的最后一次点击配对
hidePickerTip()
updateToolUI()
updateBrushParamUI()
if (tool === 'crop') {
showCropBar()
updateCropInfo()
} else {
cancelCrop()
hideCropBar()
}
renderObjects()
renderLayerPanel()
// 让蚂蚁线/浮动条按新的工具与选区状态同步(由 index.js 注入)
if (S.renderAll) S.renderAll()
}