Files
iwb-plugins-desktop/image-annotate/plugin/editor/tools.js
T
qiqi b63771f6e4 feat(image-annotate): v1.10.0 颜色语义统一、选中框改实线、选区命令归位、矢量图形补描边与填充
四个问题来自同一张界面截图,都是真缺陷。

1) 三处颜色各司其职。'#ff4444'/'#ffffff'/'#000000'/0.68 这些默认值原先散在
state.js、text.js、events.js 三处,改一处另两处不跟 —— 界面上就成了「同一个
概念三种颜色」。现在 text.js 导出 TEXT_DEFAULTS 做单点定义,state.js 与选项栏
都从这里取。三个色块统一外观但标记「生效状态」:描边宽度 0 / 底色关闭 /
图形处于描边模式时,色块显示灰色斜纹(不显示颜色本身),语义是「这里还没有
颜色」;只做半透明灰化不够,深色照样是一块黑方块。文字底色默认从纯黑 #000000
改为中性近黑 #101014(68% 透明),色块按真实不透明度渲染。选描边色时若宽度
为 0 自动给 6px,与「选底色即开底色」同一条原则。

2) 选中框从虚线改实线。虚线在修图软件里的语义是像素选区(蚂蚁线),文字外面
套一圈虚线会被当成「多出来一个删不掉的选区」。objects.js 的文字/形状、
layers.js 的位图图层三处同步改为实线,虚线只留给真正的像素选区。

3) 选区命令(全选/反选/取消)归位到选区工具。它们操作的是像素选区,跟文字对象
无关:以前挂在「选中文字/图形」的选项栏里,选中文字就冒出来;而矩形/套索
选区工具反而没有。现在选区工具有,选择工具「未选中任何元素」时也有。

4) 矢量图形补上描边色与填充色。每个形状新增独立 fillColor;描边色不再另起一份,
直接复用主色(左侧色板/吸管/选项栏一个真相源,四处永远同步)。fillColor===null
表示跟随描边色,于是新画的实心图形是同色实心,换主色整块跟着变。
矩形/圆形/钢笔/箭头的选项栏都出「描边 ■ / 填充 ■」色块(箭头无填充区域,只给
描边色);选中对象读它自己的值,没选中时改的是新建默认值。选填充色即自动切
实心,色块从斜纹变成实际颜色。「样式 描边/实心」也改成读选中对象自己的 fill
(以前只看全局默认值,选中已实心的矩形却高亮「描边」,和画面反着来)。

顺带简化:文本样式与形状颜色共用同一套色块控件与 CSS,is-off 用斜纹 +
虚线边框;底色色块用 --sw-a 变量体现半透明。

harness 162 → 172 条全通(新增:默认色不写死、色块生效态、选区命令归位、
选中框实线覆盖率 ≥0.85、图形描边/填充色与实际像素);validate 9/9。
harness 自身两处改法:清选中改用「切到别的工具再切回」(画布上早有别的用例
留下的图形,点空白会点到它们);像素断言改成全画布统计同色像素
(矢量画布含 overlayPad 外扩,按图片坐标换算单点会采到别处)。
2026-11-08 21:24:38 +08:00

484 lines
19 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 { resetOverlayTransform } from './scale.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'
import { rememberColor } from './recent-colors.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
}
/** 圆角半径:夹在短边一半以内,避免圆角把矩形吃掉变胶囊/消失 */
function roundedRadius(s, w, h) {
const r = Number(s && s.radius) || 0
if (r <= 0) return 0
return Math.min(r, Math.min(w, h) / 2)
}
/** 圆角矩形路径:不用 ctx.roundRect(老浏览器没有),手写 arcs,行为可控 */
function roundRectPath(ctx, x, y, w, h, r) {
const rr = Math.min(r, Math.min(w, h) / 2)
ctx.moveTo(x + rr, y)
ctx.arcTo(x + w, y, x + w, y + h, rr)
ctx.arcTo(x + w, y + h, x, y + h, rr)
ctx.arcTo(x, y + h, x, y, rr)
ctx.arcTo(x, y, x + w, y, rr)
ctx.closePath()
}
/** 按形状对象绘制(矩形/箭头),预览与最终渲染共用 */
/** 形状描边色:每个形状自己存 color(v1.10 起选项栏可单独调) */
export function strokeOf(s) { return (s && s.color) || S.color }
/** 形状填充色:自己设过 fillColor 就用它,否则跟随描边色(同色实心是默认手感) */
export function fillOf(s) { return (s && s.fillColor) || strokeOf(s) }
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 = strokeOf(s)
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 = fillOf(s); ctx.fill() } ctx.stroke() }
} else if (s.type === 'rect') {
const rx = Math.min(s.x1, s.x2), ry = Math.min(s.y1, s.y2), rw = Math.abs(s.x2 - s.x1), rh = Math.abs(s.y2 - s.y1)
const radius = roundedRadius(s, rw, rh)
if (radius > 0) {
ctx.beginPath()
roundRectPath(ctx, rx, ry, rw, rh, radius)
if (s.fill) { ctx.fillStyle = fillOf(s); ctx.fill() }
ctx.stroke()
} else {
if (s.fill) { ctx.fillStyle = fillOf(s); 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 = fillOf(s); ctx.fill() }
ctx.stroke()
} else {
ctx.fillStyle = strokeOf(s)
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
ctx.save()
ctx.setTransform(1, 0, 0, 1, 0, 0)
ctx.clearRect(0, 0, ctx.canvas.width, ctx.canvas.height)
ctx.restore()
resetOverlayTransform(ctx)
}
/** 圆形笔刷光标:画在独立 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
// 只有「确认型」改色才进最近使用:拖 SV 时 skipHistory=true 每帧都调,
// 全记进去会把最近色刷成一串相邻色,毫无用处。
if (!skipHistory) rememberColor(color)
updateColorUI()
const t = getSelectedText()
if (t && !t.locked && t.color !== S.color) {
if (!skipHistory) saveSnapshot()
t.color = S.color
renderObjects()
}
const sh = getSelectedShape()
if (sh && !sh.locked && S.tool !== 'text' && sh.color !== S.color) {
if (!skipHistory) saveSnapshot()
sh.color = S.color
renderObjects()
}
}
/** 切换工具(工具栏按钮、快捷键、调色板吸色共用)。保留同类形状选中以便继续编辑。 */
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()
}