feat(image-annotate): v1.9.0 文字样式包、吸附参考线、圆角与最近色、复制到剪贴板

文字从「字号 + 颜色」扩到完整样式:字重(常规/粗/特粗)、对齐(左/中/右)、
行距、描边、底色块、多行(textarea + Shift+Enter)。新增叶子模块 text.js,
fontOf / textMetrics / textBox / drawTextObject 成为唯一事实来源,
objects.js(预览/命中/包围盒)与 layers.js(栅格化)共用,避免量一套画一套;
描边与底色撑大包围盒,手柄、吸附、缩略图随之变化。单行无描边无底色的老文字
包围盒与旧实现逐像素一致,老作业打开不变形。

吸附参考线:snap.js 只做纯计算。目标线为画布 0/中/满 + 其他可见元素的左中右、
上中下;阈值 6 屏幕像素按 viewScale() 折回图片像素,磁力不随缩放变大;
命中画洋红参考线(区别于选中框的橙),松手清空;Alt 全程禁用。
位图/文字/形状三条拖动路径都接,文字需补 b.x - t.x 原点偏移。

矩形圆角:shapeRadius 进 drawShape,半径夹到 min(w,h)/2,路径手写 arcTo
(不用 ctx.roundRect,老内核没有)。最近使用颜色最多 8 个,存 ctx.settings
跨会话保留,只有落定的改色才记录;色板改用事件委托以覆盖动态插入的色块。

导出「复制」:结果编成 PNG 写 ClipboardItem,可直接粘进聊天窗口/后台上传框
且不关闭编辑器。优先 createImageBitmap 绕开宿主 CSP 的 img-src 限制;
非安全上下文无 navigator.clipboard 时明确提示改用「导出」而非静默失败。

顺带修:选项栏中文双字标签加 white-space:nowrap(否则 36px 一行内竖排成
「常/规」);.iwb-editor-optionbar-tip 补基础样式(原来只有 display:none,
裸 span 参与 flex 收缩被挤成两行贴边);文字工具的 hint 移到按钮之后,
放不下时让说明滚出视野而不是把操作按钮顶没。

harness 140 → 158 条,全部通过;validate 9/9。
This commit is contained in:
qiqi committed 2026-11-08 20:27:32 +08:00
1 parent 040b08fe28
commit e699c22fa0
17 files changed
+1678 -99

No files matched your search

+62 -1
View File
@@ -563,10 +563,17 @@
border: 2px solid #4488ff;
border-radius: 4px;
font-size: 14px;
line-height: 1.35;
/* textarea:默认会显示右下角拖拽柄与滚动条,画布上的就地输入框都不要 */
resize: none;
overflow: hidden;
white-space: pre;
background: rgba(255, 255, 255, 0.95);
color: #1e1e2e;
z-index: 10;
min-width: 120px;
min-height: 30px;
font-family: inherit;
}
.iwb-editor-text-input:focus { outline: none; box-shadow: 0 0 0 3px rgba(68, 136, 255, 0.3); }
@@ -1434,6 +1441,12 @@
}
.iwb-editor-optionbar-label { color: #7f849c; font-weight: 600; white-space: nowrap; }
.iwb-editor-optionbar-body { display: flex; align-items: center; gap: 8px; flex: 1 1 auto; min-width: 0; }
/* 右端通用快捷键提示。原来只有 @media 里的 display:none,没有任何基础样式,
于是它作为裸 span 参与 flex 收缩,被挤成两行还贴到右边缘外。 */
.iwb-editor-optionbar-tip {
flex: 0 0 auto; white-space: nowrap;
color: #6c7086; font-size: 11px; padding-left: 4px;
}
.iwb-opt-label { color: #a6adc8; white-space: nowrap; }
.iwb-opt-btn {
background: #313244; color: #cdd6f4; border: 1px solid transparent; border-radius: 5px;
@@ -1446,7 +1459,10 @@
border: 1px solid #45475a; border-radius: 5px; text-align: center; font-size: 12px;
}
.iwb-opt-current { color: #e8a735; font-weight: 600; white-space: nowrap; }
.iwb-opt-hint { color: #7f849c; font-size: 11px; margin-left: auto; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
/* hint 是「说明」不是「控件」:不许被压缩。
早先带 text-overflow:ellipsis,在 36px 高的选项栏里会被压成「双击改…」这种半截文案,
比不显示更误导人;现在由父级 overflow-x 决定是完整显示还是整体滚出视野。 */
.iwb-opt-hint { color: #7f849c; font-size: 11px; margin-left: auto; white-space: nowrap; flex: 0 0 auto; }
.iwb-editor-more-wrap, .iwb-editor-export-settings-wrap { position: relative; flex: 0 0 auto; z-index: 45; }
.iwb-editor-more-btn, .iwb-editor-panel-toggle, .iwb-editor-export-settings-btn {
@@ -1858,3 +1874,48 @@
border-color: #89b4fa;
color: #cdd6f4;
}
/* ================================================================
v1.9:文字样式控件 / 圆角 / 最近使用颜色 / 复制按钮
================================================================ */
/* 选项栏里的原生颜色框(描边色 / 底色):压成和数字框同高的小方块 */
.iwb-opt-color {
width: 22px;
height: 20px;
padding: 0;
flex: 0 0 auto;
border: 1px solid #45475a;
border-radius: 4px;
background: transparent;
cursor: pointer;
}
.iwb-opt-color::-webkit-color-swatch-wrapper { padding: 2px; }
.iwb-opt-color::-webkit-color-swatch { border: 0; border-radius: 3px; }
/* 「最近使用」:色板弹层里 4 列 × 2 行,空的时候整块隐藏(不占位) */
.iwb-editor-color-pop .iwb-editor-recent-colors {
display: grid;
grid-template-columns: repeat(4, 18px);
grid-auto-rows: 18px;
gap: 5px;
flex: 0 0 auto;
align-content: center;
}
.iwb-editor-recent-colors[hidden] { display: none; }
.iwb-editor-color-pop .iwb-editor-recent-colors .iwb-editor-color-panel-swatch {
width: 18px;
height: 18px;
padding: 0;
border: 0;
border-radius: 50%;
cursor: pointer;
}
.iwb-editor-color-pop .iwb-editor-recent-colors .iwb-editor-color-panel-swatch:hover { transform: scale(1.12); }
/* 复制到剪贴板:与「导出」同尺寸但用低饱和色,避免两个绿色按钮抢眼 */
.iwb-editor-btn-copy { background: #313244 !important; color: #cdd6f4 !important; }
.iwb-editor-btn-copy:hover { background: #3b3d52 !important; }
/* 选项栏按钮里是中文双字标签(常规/特粗/底色),不给 nowrap 会被挤成竖排 */
.iwb-editor-optionbar-body .iwb-opt-btn { white-space: nowrap; }
+6 -2
View File
@@ -79,13 +79,14 @@ import { bindEvents } from './events.js'
<div class="iwb-editor-export-note">一次只输出一个结果;设置会记住</div>
</div>
</div>
<button class="iwb-editor-btn iwb-editor-btn-copy" data-action="copyClipboard" title="复制当前结果到系统剪贴板(可直接粘到聊天窗口/后台),不关闭编辑器">复制</button>
<button class="iwb-editor-btn iwb-editor-btn-download" data-action="download" title="导出当前这一张(不关闭编辑器)">导出</button>
</div>
</div>
<div class="iwb-editor-optionbar">
<span class="iwb-editor-optionbar-label">工具选项</span>
<div class="iwb-editor-optionbar-body"></div>
<span class="iwb-editor-optionbar-tip">选区也可右键;Ctrl+J 复制 · Delete 清除 · Ctrl+D 取消</span>
<span class="iwb-editor-optionbar-tip" title="选中后还可右键;Ctrl+J 复制 · Delete 清除 · Ctrl+D 取消选区">Ctrl+J 复制 · Delete 清除</span>
</div>
<div class="iwb-editor-main">
@@ -114,7 +115,8 @@ import { bindEvents } from './events.js'
<canvas class="iwb-editor-selection-overlay"></canvas>
<canvas class="iwb-editor-cursor-overlay"></canvas>
</div>
<input class="iwb-editor-text-input" type="text" placeholder="输入文字,Enter确认,Esc取消">
<!-- v1.9:input → textarea,支持 Shift+Enter 换行(Enter 仍是确认) -->
<textarea class="iwb-editor-text-input" rows="1" wrap="off" placeholder="输入文字,Enter 确认,Shift+Enter 换行" spellcheck="false"></textarea>
<div class="iwb-editor-picker-tip"><span class="iwb-editor-picker-chip"></span><span class="iwb-editor-picker-hex">#ffffff</span></div>
<!-- 裁剪参数已迁入选项栏(v1.2.2),画布下方浮窗删除 -->
<div class="iwb-editor-sel-bar">
@@ -239,6 +241,8 @@ import { bindEvents } from './events.js'
<input class="iwb-editor-color-hex-input" value="#ff4444" maxlength="7" spellcheck="false" autocomplete="off" title="十六进制颜色,回车生效">
</div>
<span class="iwb-color-pop-sep"></span>
<!-- 最近使用(v1.9):由 recent-colors.js 动态填充,空的时候整行隐藏 -->
<div class="iwb-editor-recent-colors" hidden title="最近使用"></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="#ff8a00" style="background:#ff8a00" title="#ff8a00"></button>
+199 -14
View File
@@ -15,9 +15,10 @@ import { beginMarquee, updateMarquee, endMarquee, beginLasso, updateLasso, endLa
import { runCommand, toast } from './commands.js'
import { showSelectionContext, hideSelectionContext } from './floating.js'
import { applyConstraintDrag, cancelCrop, clearOverlay, confirmCrop, drawCropPreview, hideCropBar, hitCropHandle, insideRect, resizeCropRect, setConstraint, showCropBar, updateCropInfo } from './crop.js'
import { applyShapeHandle, beginPenEdit, beginShapeHandleDrag, beginTextRotate, beginTextScaleDrag, commitTextInput, deleteSelectedShape, deleteSelectedText, exitPenEdit, getPenEditingShape, getSelectedShape, getSelectedText, hideTextInput, hitAnyObject, hitPenEdgeInsert, hitPenPoint, hitShapeHandle, hitShapeLayer, hitTextHandle, hitTextLayer, hitTopmost, moveLayer, renderObjects, selectNeighborLayer, selectUnit, shapeBounds, showTextInput } from './objects.js'
import { applyShapeHandle, beginPenEdit, beginShapeHandleDrag, beginTextRotate, beginTextScaleDrag, commitTextInput, deleteSelectedShape, deleteSelectedText, exitPenEdit, getPenEditingShape, getSelectedShape, getSelectedText, hideTextInput, hitAnyObject, hitPenEdgeInsert, hitPenPoint, hitShapeHandle, hitShapeLayer, hitTextHandle, hitTextLayer, hitTopmost, moveLayer, otherObjectBoxes, renderObjects, selectNeighborLayer, selectUnit, shapeBounds, showTextInput, textBounds } from './objects.js'
import { snapMove } from './snap.js'
import { cancelImagePlacement, confirmImagePlacement, drawPlacementPreview, hitPlacementHandle, insidePlacementRect, resizePlacement } from './placement.js'
import { close, exportResult } from './index.js'
import { close, copyResult, exportResult } from './index.js'
import { loadImage } from './dom.js'
import { pushHistory, redo, resetDraw, restoreOriginal, restoreAll, saveSnapshot, snapshotState, undo } from './history.js'
import { applyQuickEffect, setEffectValue } from './effects.js'
@@ -344,6 +345,8 @@ import { hexToRgb, parseRatio, rgbToHex } from '../vendor/image-math.js'
}
function onMouseMove(e) {
// 记下修饰键:拖动按 Alt 时临时关掉吸附(想停在「差一点点」的位置时用)
S._altDown = !!e.altKey
// 图片放置拖拽
if (S.placingImage && S.placingHandle && S.placingStart) {
onPlacementDragMove(e); return
@@ -416,8 +419,24 @@ import { hexToRgb, parseRatio, rgbToHex } from '../vendor/image-math.js'
if (S.textDrag.mode === 'move') {
const dx = pos0.x - S.textDrag.start.x
const dy = pos0.y - S.textDrag.start.y
t.x = clamp(S.textDrag.layer.x + dx, 0, Math.max(0, S.imgW - 4))
t.y = clamp(S.textDrag.layer.y + dy, 0, Math.max(0, S.imgH - 4))
let nx = clamp(S.textDrag.layer.x + dx, 0, Math.max(0, S.imgW - 4))
let ny = clamp(S.textDrag.layer.y + dy, 0, Math.max(0, S.imgH - 4))
// 吸附:按住 Alt 临时关掉(要对齐到「差一点点」的位置时用)
if (!S._altDown) {
const b = textBounds(t)
// b 是「含描边/底色的包围盒」,t.x/t.y 是文字原点:两者差一个固定偏移,
// 用原点当包围盒左上会把吸附中心算偏 strokeWidth/2,边线永远差几像素吸不上
const offX = b.x - t.x
const offY = b.y - t.y
const s = snapMove({ x: nx + offX, y: ny + offY, w: b.w, h: b.h }, otherObjectBoxes(t))
nx += s.dx
ny += s.dy
S.guides = s.guides.length ? s.guides : null
} else {
S.guides = null
}
t.x = nx
t.y = ny
} else if (S.textDrag.mode === 'rotate') {
const st = S.textDrag
const a1 = Math.atan2(pos0.y - st.cy, pos0.x - st.cx)
@@ -457,8 +476,17 @@ import { hexToRgb, parseRatio, rgbToHex } from '../vendor/image-math.js'
const dx = pos0.x - S.shapeDrag.start.x
const dy = pos0.y - S.shapeDrag.start.y
const b = shapeBounds(S.shapeDrag.shape)
const cdx = clamp(dx, -b.x, Math.max(-b.x, S.imgW - (b.x + b.w)))
const cdy = clamp(dy, -b.y, Math.max(-b.y, S.imgH - (b.y + b.h)))
let cdx = clamp(dx, -b.x, Math.max(-b.x, S.imgW - (b.x + b.w)))
let cdy = clamp(dy, -b.y, Math.max(-b.y, S.imgH - (b.y + b.h)))
if (!S._altDown) {
const box = { x: b.x + cdx, y: b.y + cdy, w: b.w, h: b.h }
const s = snapMove(box, otherObjectBoxes(sh))
cdx += s.dx
cdy += s.dy
S.guides = s.guides.length ? s.guides : null
} else {
S.guides = null
}
if (sh.type === 'pen') {
sh.pts = (S.shapeDrag.shape.pts || []).map(p => ({ x: p.x + cdx, y: p.y + cdy }))
} else {
@@ -510,6 +538,7 @@ import { hexToRgb, parseRatio, rgbToHex } from '../vendor/image-math.js'
lw: Math.max(1, S.shapeLineWidth),
lineWidth: Math.max(1, S.shapeLineWidth),
fill: S.tool === 'rect' || S.tool === 'circle' ? !!S.rectFill : false,
radius: S.tool === 'rect' ? Math.max(0, S.shapeRadius) : 0,
opacity: 1,
visible: true
}
@@ -622,6 +651,8 @@ import { hexToRgb, parseRatio, rgbToHex } from '../vendor/image-math.js'
}
}
S.textDrag = null
S.guides = null // 松手即撤掉吸附参考线(重绘 overlay 才能真的擦掉)
renderObjects()
renderLayerPanel()
return
}
@@ -639,6 +670,7 @@ import { hexToRgb, parseRatio, rgbToHex } from '../vendor/image-math.js'
}
}
S.bitmapDrag = null
S.guides = null
renderObjects()
renderLayerPanel()
return
@@ -656,6 +688,8 @@ import { hexToRgb, parseRatio, rgbToHex } from '../vendor/image-math.js'
}
}
S.shapeDrag = null
S.guides = null
renderObjects()
renderLayerPanel()
return
}
@@ -708,6 +742,7 @@ import { hexToRgb, parseRatio, rgbToHex } from '../vendor/image-math.js'
color: S.color,
lw: Math.max(1, S.shapeLineWidth),
fill: S.tool === 'rect' || S.tool === 'circle' ? !!S.rectFill : false,
radius: S.tool === 'rect' ? Math.max(0, S.shapeRadius) : 0,
opacity: 1,
visible: true,
locked: false,
@@ -946,6 +981,51 @@ import { hexToRgb, parseRatio, rgbToHex } from '../vendor/image-math.js'
const SHAPE_NAMES = { rect: '矩形', circle: '圆形', arrow: '箭头', pen: '钢笔路径' }
// ---- 文字样式(v1.9):字重 / 对齐 / 行距 / 描边 / 底色 ----
// 控件既作用于「当前选中的文字」,也写回「新建文字的默认值」:
// 没选中时光调参数就是调下一次输入的样子,选中后调则立刻改这一段。
const TEXT_STYLE_STATE_KEY = {
fontWeight: 'textWeight', align: 'textAlign', lineHeight: 'textLineHeight',
strokeWidth: 'textStrokeWidth', strokeColor: 'textStrokeColor',
bgFill: 'textBgFill', bgColor: 'textBgColor'
}
/** 读样式:t 有值读对象自己的(老对象缺字段时回退到默认),否则读新建默认值 */
function textStyleValues(t) {
const pick = (objKey, stateKey, dflt) => {
const raw = t ? t[objKey] : S[stateKey]
return raw == null ? dflt : raw
}
return {
fontWeight: String(pick('fontWeight', 'textWeight', 'bold')),
align: pick('align', 'textAlign', 'left'),
lineHeight: Number(pick('lineHeight', 'textLineHeight', 1.25)) || 1.25,
strokeWidth: Math.max(0, Number(pick('strokeWidth', 'textStrokeWidth', 0)) || 0),
strokeColor: pick('strokeColor', 'textStrokeColor', '#ffffff'),
bgFill: !!pick('bgFill', 'textBgFill', false),
bgColor: pick('bgColor', 'textBgColor', '#000000')
}
}
function textStyleHTML(t) {
const v = textStyleValues(t)
const wBtn = (val, label, title) =>
`<button class="iwb-opt-btn${v.fontWeight === val ? ' active' : ''}" data-opt-text="fontWeight" data-value="${val}" title="${title}">${label}</button>`
const aBtn = (val, label, title) =>
`<button class="iwb-opt-btn${v.align === val ? ' active' : ''}" data-opt-text="align" data-value="${val}" title="${title}">${label}</button>`
return `<span class="iwb-opt-sep"></span>
<span class="iwb-opt-label">字重</span>${wBtn('normal', '常规', '常规字重')}${wBtn('bold', '粗', '粗体(默认)')}${wBtn('900', '特粗', '特粗,封面标题用')}
<span class="iwb-opt-label">对齐</span>${aBtn('left', '左', '多行时按左缘对齐')}${aBtn('center', '中', '多行时居中')}${aBtn('right', '右', '多行时按右缘对齐')}
<span class="iwb-opt-label">行距</span>
<input type="number" class="iwb-opt-num" data-opt="textLineHeight" min="80" max="300" step="5" value="${Math.round(v.lineHeight * 100)}"><span class="iwb-opt-unit">%</span>
<span class="iwb-opt-sep"></span>
<span class="iwb-opt-label">描边</span>
<input type="number" class="iwb-opt-num" data-opt="textStrokeWidth" min="0" max="40" step="1" value="${Math.round(v.strokeWidth)}"><span class="iwb-opt-unit">px</span>
<input type="color" class="iwb-opt-color" data-opt-color="strokeColor" value="${v.strokeColor}" title="描边颜色">
<button class="iwb-opt-btn${v.bgFill ? ' active' : ''}" data-opt-text="bgFill" data-value="${v.bgFill ? '0' : '1'}" title="给文字加一块半透明底色,压在花背景上也能看清">底色</button>
<input type="color" class="iwb-opt-color" data-opt-color="bgColor" value="${v.bgColor}" title="底色颜色(55% 透明)">`
}
/** 选择工具:只有选中了元素才出该元素的参数。
* 用户裁定 2026-11-04:选中矩形/钢笔后要能就地切描边/实心、改描边粗细,
* 不必再切回绘制工具 —— 所以这里复用绘制工具同一套控件与写回路径。 */
@@ -972,6 +1052,8 @@ import { hexToRgb, parseRatio, rgbToHex } from '../vendor/image-math.js'
return `<span class="iwb-opt-current">已选中:${SHAPE_NAMES[t] || t}</span>`
+ rangeOpt('shapeLineWidth', '线宽', 1, 60, lw, '')
+ presetDots('shapeLineWidth', [1, 2, 3, 6, 10, 16, 24])
// 圆角只对矩形有意义(圆形本来就是圆的,箭头/钢笔没有这个概念)
+ (t === 'rect' ? rangeOpt('shapeRadius', '圆角', 0, 200, Math.round(sh.radius || 0), 'px') : '')
+ (t === 'arrow' ? '' : fillStyleHTML(owner))
+ (t === 'pen' && !sh.closed
? '<span class="iwb-opt-hint">这条钢笔路径未闭合,实心不生效;点回起点闭合后即可填充</span>'
@@ -983,8 +1065,11 @@ import { hexToRgb, parseRatio, rgbToHex } from '../vendor/image-math.js'
if (text) {
return `<span class="iwb-opt-current">已选中:文字</span>`
+ rangeOpt('textSize', '字号', 8, 400, Math.round(text.fontSize || S.textSize), 'px')
+ '<span class="iwb-opt-hint">双击文字改内容,拖动移动,手柄缩放</span>'
+ textStyleHTML(text)
// 控件齐全时这一行很挤,说明文字必须排在按钮之后:
// 真放不下时宁可把 hint 滚出视野,也不能把「复制/取消选区」这些按钮顶没了
+ selCmdHTML()
+ '<span class="iwb-opt-hint">双击改内容 · 拖动手柄缩放</span>'
}
return `<span class="iwb-opt-current">当前工具:选择 / 移动</span>
<span class="iwb-opt-hint">点中矩形/圆形/钢笔/文字后,这里会出现它的描边、实心与粗细</span>`
@@ -1009,6 +1094,7 @@ import { hexToRgb, parseRatio, rgbToHex } from '../vendor/image-math.js'
if (tool === 'rect' || tool === 'circle') {
return rangeOpt('shapeLineWidth', '线宽', 1, 60, S.shapeLineWidth, '')
+ presetDots('shapeLineWidth', [1, 2, 3, 6, 10, 16, 24])
+ (tool === 'rect' ? rangeOpt('shapeRadius', '圆角', 0, 200, S.shapeRadius, 'px') : '')
+ fillStyleHTML('rect')
}
if (tool === 'arrow') {
@@ -1024,7 +1110,8 @@ import { hexToRgb, parseRatio, rgbToHex } from '../vendor/image-math.js'
}
if (tool === 'text') {
return rangeOpt('textSize', '字号', 8, 400, S.textSize, 'px')
+ '<span class="iwb-opt-hint">点画布输入文字,Enter 确认</span>'
+ textStyleHTML(null)
+ '<span class="iwb-opt-hint">点画布输入文字,Enter 确认,Shift+Enter 换行</span>'
}
if (tool === 'marquee') {
return `<span class="iwb-opt-label">形状</span>
@@ -1068,7 +1155,10 @@ import { hexToRgb, parseRatio, rgbToHex } from '../vendor/image-math.js'
if (key === 'brushHardness') return S.brushHardness
if (key === 'brushOpacity') return Math.round(S.brushOpacity * 100)
if (key === 'shapeLineWidth') return selShape ? Math.max(1, Math.round(selShape.lw || S.shapeLineWidth)) : S.shapeLineWidth
if (key === 'shapeRadius') return selShape && selShape.type === 'rect' ? Math.round(selShape.radius || 0) : S.shapeRadius
if (key === 'textSize') return selText ? Math.round(selText.fontSize || S.textSize) : S.textSize
if (key === 'textLineHeight') return Math.round((selText ? (Number(selText.lineHeight) || S.textLineHeight) : S.textLineHeight) * 100)
if (key === 'textStrokeWidth') return Math.round(selText ? (Number(selText.strokeWidth) || 0) : S.textStrokeWidth)
if (key === 'feather') return S.selectionFeather
return ''
}
@@ -1093,6 +1183,18 @@ import { hexToRgb, parseRatio, rgbToHex } from '../vendor/image-math.js'
}
btn.classList.toggle('active', !!cur === (btn.dataset.value === 'fill'))
})
// 文字样式按钮组与两个颜色框:选中对象的值优先,没选中就显示新建默认值
const sv = textStyleValues(selText)
body.querySelectorAll('[data-opt-text]').forEach(btn => {
const k = btn.dataset.optText
const cur = k === 'bgFill' ? (sv.bgFill ? '1' : '0') : String(sv[k])
btn.classList.toggle('active', cur === btn.dataset.value)
})
body.querySelectorAll('[data-opt-color]').forEach(inp => {
if (document.activeElement === inp) return
const v = sv[inp.dataset.optColor]
if (v && String(inp.value).toLowerCase() !== String(v).toLowerCase()) inp.value = v
})
}
/** 状态栏:缩放 / 尺寸 / 光标 / 选区 / 当前层 / 工具 */
@@ -1140,6 +1242,45 @@ import { hexToRgb, parseRatio, rgbToHex } from '../vendor/image-math.js'
if (committed) textSnapDone = false
}
let textStyleSnapDone = false
/**
* 应用一条文字样式。
* 两件事一起做:写回「新建默认值」S.*,以及改当前选中的那段文字。
* 拖动滑杆/连续点按钮时只在第一次拍快照(一次调整 = 一次撤销)。
*/
function applyTextStyle(key, raw, committed) {
const stateKey = TEXT_STYLE_STATE_KEY[key]
if (!stateKey) return
let value = raw
// data-value 是字符串:'0' 也是真值,必须显式判,不能直接 !!raw
if (key === 'bgFill') value = raw === true || raw === 1 || raw === '1' || raw === 'true'
else if (key === 'lineHeight') value = clamp(Number(raw) || 125, 80, 300) / 100
else if (key === 'strokeWidth') value = clamp(Number(raw) || 0, 0, 40)
else if (key === 'strokeColor' || key === 'bgColor') value = String(raw || '#000000').toLowerCase()
else value = String(raw)
S[stateKey] = value
const t = getSelectedText()
if (!t || t.locked) { textStyleSnapDone = false; return }
if (committed || !textStyleSnapDone) { saveSnapshot('文字样式'); textStyleSnapDone = true }
t[key] = value
renderObjects()
if (committed) textStyleSnapDone = false
}
let radiusSnapDone = false
/** 圆角只对矩形有意义:改默认值 + 改选中的那个矩形 */
function applyShapeRadius(committed) {
const sh = getSelectedShape()
if (!sh || sh.locked || sh.type !== 'rect') { radiusSnapDone = false; return }
if (committed || !radiusSnapDone) { saveSnapshot('圆角'); radiusSnapDone = true }
sh.radius = S.shapeRadius
renderObjects()
if (committed) radiusSnapDone = false
}
/** 形状描边/实心:既改下次新建的默认值,也改当前选中的那个。
* owner='rect' 作用于矩形/圆,owner='pen' 作用于钢笔闭合路径。 */
function setShapeFill(fill, owner) {
@@ -1183,6 +1324,13 @@ import { hexToRgb, parseRatio, rgbToHex } from '../vendor/image-math.js'
} else if (key === 'textSize') {
S.textSize = clamp(safe || 32, 8, 400)
applyTextSize(committed)
} else if (key === 'textLineHeight') {
applyTextStyle('lineHeight', safe || 125, committed)
} else if (key === 'textStrokeWidth') {
applyTextStyle('strokeWidth', safe, committed)
} else if (key === 'shapeRadius') {
S.shapeRadius = clamp(safe, 0, 400)
applyShapeRadius(committed)
} else if (key === 'feather') {
S.selectionFeather = clamp(safe, 0, 20)
if (S.selection && S.selection.active) S.selection.feather = S.selectionFeather
@@ -1268,8 +1416,28 @@ import { hexToRgb, parseRatio, rgbToHex } from '../vendor/image-math.js'
// 滑杆拖动中(input)与松手/失焦(change)走同一条写回路径,
// committed 只决定「要不要顺手记一步历史」,不影响参数生效。
body.addEventListener('input', (e) => setOptionFromControl(e.target, false))
body.addEventListener('change', (e) => setOptionFromControl(e.target, true))
body.addEventListener('change', (e) => {
// 原生颜色框:拖动时只派发 input、关闭取色器才派发 change。
// 只认 change,保证「改一次颜色 = 一步撤销」,不在拖动途中连拍快照。
const colorEl = e.target.closest ? e.target.closest('[data-opt-color]') : null
if (colorEl) {
e.stopPropagation()
applyTextStyle(colorEl.dataset.optColor, colorEl.value, true)
syncOptionBar()
return
}
setOptionFromControl(e.target, true)
})
body.addEventListener('click', (e) => {
// 文字样式按钮(字重 / 对齐 / 底色开关)
const textBtn = e.target.closest('[data-opt-text]')
if (textBtn) {
e.stopPropagation()
const k = textBtn.dataset.optText
applyTextStyle(k, textBtn.dataset.value, true)
syncOptionBar()
return
}
const shapeBtn = e.target.closest('[data-opt="shape"]')
if (shapeBtn) {
e.stopPropagation()
@@ -1467,7 +1635,16 @@ import { hexToRgb, parseRatio, rgbToHex } from '../vendor/image-math.js'
}
const panelHexInput = runtime.el.querySelector('.iwb-editor-color-hex-input')
if (panelHexInput) panelHexInput.addEventListener('change', () => { if (/^#[0-9a-f]{6}$/i.test(panelHexInput.value)) setPanelColor(panelHexInput.value) })
runtime.el.querySelectorAll('.iwb-editor-color-panel-swatch').forEach(btn => btn.addEventListener('click', (e) => { e.stopPropagation(); setPanelColor(btn.dataset.panelColor) }))
// 色块统一走委托:静态 12 色 + 动态插入的「最近使用」都要能点,
// 一次性 querySelectorAll 绑定会漏掉后来插进来的按钮
if (pop) {
pop.addEventListener('click', (e) => {
const btn = e.target.closest('[data-panel-color]')
if (!btn) return
e.stopPropagation()
setPanelColor(btn.dataset.panelColor)
})
}
const palettePick = runtime.el.querySelector('[data-action="palettePick"]')
if (palettePick) {
palettePick.addEventListener('mousedown', (e) => e.stopPropagation())
@@ -1658,6 +1835,7 @@ import { hexToRgb, parseRatio, rgbToHex } from '../vendor/image-math.js'
// 底部
bindIf('[data-action="cancel"]', 'click', close)
bindIf('[data-action="download"]', 'click', () => exportResult('download'))
bindIf('[data-action="copyClipboard"]', 'click', () => copyResult())
bindIf('[data-action="newNode"]', 'click', () => exportResult('newNode'))
bindIf('[data-action="replace"]', 'click', () => exportResult('replace'))
}
@@ -1670,14 +1848,21 @@ import { hexToRgb, parseRatio, rgbToHex } from '../vendor/image-math.js'
S.canvasWrap.addEventListener('wheel', onWheel, { passive: false })
}
/** 文字输入框:Enter 提交、Esc 取消 */
/** 文字输入框:Enter 提交、Shift+Enter 换行、Esc 取消(v1.9 换成 textarea 支持多行) */
function bindTextInput() {
// 文字输入
const textInput = runtime.el.querySelector('.iwb-editor-text-input')
textInput && textInput.addEventListener('mousedown', (e) => e.stopPropagation())
textInput && textInput.addEventListener('keydown', (e) => {
if (!textInput) return
textInput.addEventListener('mousedown', (e) => e.stopPropagation())
// 边打边按内容撑高:textarea 不自动长高,多行标题会被压在两行里看不清
const autosize = () => {
textInput.style.height = 'auto'
textInput.style.height = (textInput.scrollHeight + 4) + 'px'
}
textInput.addEventListener('input', autosize)
textInput.addEventListener('keydown', (e) => {
e.stopPropagation()
if (e.key === 'Enter') { e.preventDefault(); commitTextInput() }
if (e.key === 'Enter' && !e.shiftKey) { e.preventDefault(); commitTextInput() }
else if (e.key === 'Escape') { e.preventDefault(); hideTextInput() }
})
}
+61
View File
@@ -294,3 +294,64 @@ import { toast } from './commands.js'
setTimeout(() => { try { URL.revokeObjectURL(url) } catch (e) { /* ignore */ } }, 2000)
toast('已下载 ' + name + '(' + Math.round(blob.size / 1024) + 'KB)', 'success')
}
/** 任意图片 blob → PNG blob(剪贴板对 image/png 支持最稳,体积在剪贴板里无所谓) */
async function toPngBlob(blob) {
// 优先 createImageBitmap:不经过 URL,绕开宿主 CSP 对 img-src 的限制
try {
if (typeof createImageBitmap === 'function') {
const bmp = await createImageBitmap(blob)
const c = document.createElement('canvas')
c.width = bmp.width
c.height = bmp.height
c.getContext('2d').drawImage(bmp, 0, 0)
if (typeof bmp.close === 'function') bmp.close()
const out = await new Promise(res => c.toBlob(b => res(b), 'image/png'))
c.width = 0
c.height = 0
if (out) return out
}
} catch (e) { /* 走 img 回退 */ }
return await new Promise((resolve) => {
const url = URL.createObjectURL(blob)
const img = new Image()
img.onload = () => {
const c = document.createElement('canvas')
c.width = img.naturalWidth
c.height = img.naturalHeight
c.getContext('2d').drawImage(img, 0, 0)
try { URL.revokeObjectURL(url) } catch (e) { /* ignore */ }
c.toBlob(b => resolve(b || blob), 'image/png')
}
img.onerror = () => {
try { URL.revokeObjectURL(url) } catch (e) { /* ignore */ }
resolve(blob)
}
img.src = url
})
}
/**
* 复制到系统剪贴板:运营场景最常用的一条路 —— 复制后直接粘进聊天窗口/小红书后台,
* 省掉「下载 → 再上传」。必须在用户手势里调用(浏览器要求),失败给可操作提示。
*/
export async function copyBlobToClipboard(blob) {
const nav = typeof navigator !== 'undefined' ? navigator : null
const CI = typeof window !== 'undefined' ? window.ClipboardItem : null
if (!nav || !nav.clipboard || typeof nav.clipboard.write !== 'function' || typeof CI !== 'function') {
toast('当前浏览器不支持复制图片,请用「导出」下载', 'warn')
return false
}
let png = blob
if (blob.type !== 'image/png') {
try { png = await toPngBlob(blob) } catch (e) { png = blob }
}
try {
await nav.clipboard.write([new CI({ 'image/png': png })])
toast('已复制到剪贴板(' + Math.round(png.size / 1024) + 'KB),可直接粘贴', 'success')
return true
} catch (e) {
toast('复制失败:' + ((e && e.message) || '浏览器拒绝了剪贴板写入') + ';可用「导出」下载', 'error')
return false
}
}
+40 -5
View File
@@ -30,14 +30,15 @@ import { HISTORY_MAX_BYTES, HISTORY_MAX_ENTRIES, historyBudgetBytes, snapshotSta
import { cancelImagePlacement } from './placement.js'
import { clearSelection, purgeVectorCanvases, renderLayerPanel } from './layers.js'
import { createEl, loadImage } from './dom.js'
import { renderObjects, hideTextInput } from './objects.js'
import { renderObjects, hideTextInput, textBounds } from './objects.js'
import { setupCanvas } from './viewport.js'
import { resetOverlayTransform } from './scale.js'
import { updateAllUI, bindLiteUI, renderOptionBar, updateStatusbar } from './events.js'
import { disposeSelection, renderSelection, selectionInfo, syncAnts, registerSelectionCommands } from './selection.js'
import { bindFloating, positionFloating, hideSelectionContext } from './floating.js'
import { renderFxPanel } from './effects.js'
import { loadExportOptions, prepareOutput, downloadBlob, bindExportUI, renderExportUI } from './export.js'
import { loadExportOptions, prepareOutput, downloadBlob, copyBlobToClipboard, bindExportUI, renderExportUI } from './export.js'
import { loadRecentColors } from './recent-colors.js'
import { toast } from './commands.js'
// ============ 打开编辑器 ============
@@ -63,6 +64,7 @@ import { toast } from './commands.js'
updateAllUI()
registerSelectionCommands()
loadExportOptions()
loadRecentColors()
bindLiteUI()
bindFloating()
bindExportUI()
@@ -274,6 +276,19 @@ import { toast } from './commands.js'
}
}
/** 复制当前结果为图片到系统剪贴板:不关编辑器、不写宿主节点 */
export async function copyResult() {
if (S.placingImage) cancelImagePlacement()
try {
const { blob } = await prepareOutput()
await copyBlobToClipboard(blob)
if (S.renderAll) S.renderAll() // 摘要里的「上次输出 …KB」要跟上
} catch (e) {
console.error('[IWB编辑器] 复制失败:', e)
toast('复制失败:' + ((e && e.message) || '图片可能跨域'), 'error')
}
}
// ============ 暴露接口 ============
/**
* 快照/历史开销观测口(性能回归与手测用):
@@ -308,9 +323,29 @@ import { toast } from './commands.js'
opacity: l.opacity == null ? 1 : l.opacity,
cssOpacity: l.canvas ? parseFloat(l.canvas.style.opacity || '1') : null
})),
shapes: S.shapeLayers.map(s => ({ id: s.id, type: s.type, lw: s.lw, fill: !!s.fill, closed: !!s.closed, z: s.z, color: s.color })),
texts: S.textLayers.map(t => ({ id: t.id, text: t.text })),
selectedShapeId: S.selectedShapeId,
shapes: S.shapeLayers.map(s => ({ id: s.id, type: s.type, lw: s.lw, fill: !!s.fill, closed: !!s.closed, z: s.z, color: s.color, radius: s.radius || 0, x1: Math.round(s.x1 || 0), y1: Math.round(s.y1 || 0), x2: Math.round(s.x2 || 0), y2: Math.round(s.y2 || 0) })),
texts: S.textLayers.map(t => ({
id: t.id, text: t.text, x: t.x, y: t.y, fontSize: t.fontSize, color: t.color,
fontWeight: t.fontWeight, align: t.align, lineHeight: t.lineHeight,
strokeWidth: t.strokeWidth, strokeColor: t.strokeColor, bgFill: !!t.bgFill, bgColor: t.bgColor,
// 包围盒:吸附/多行/底色/描边的断言都靠它,和绘制共用同一套度量
box: (() => { const b = textBounds(t); return { x: Math.round(b.x), y: Math.round(b.y), w: Math.round(b.w), h: Math.round(b.h) } })()
})),
// 吸附参考线(拖动中才有)与最近使用颜色:交互回归用
guides: S.guides ? S.guides.map(g => ({ axis: g.axis, at: Math.round(g.at * 10) / 10 })) : [],
recentColors: (S.recentColors || []).slice(),
textDefaults: {
weight: S.textWeight, align: S.textAlign, lineHeight: S.textLineHeight,
strokeWidth: S.textStrokeWidth, strokeColor: S.textStrokeColor,
bgFill: S.textBgFill, bgColor: S.textBgColor
}, selectedShapeId: S.selectedShapeId,
// 光标所在的图片坐标(状态栏同源):换算问题的第一现场证据
lastPos: S.lastPos ? { x: Math.round(S.lastPos.x), y: Math.round(S.lastPos.y) } : null,
// 当前正在进行的拖拽类型:move 才是拖动本体,handle/rotate 说明点到了控制点
drag: S.shapeDrag ? ('shape:' + S.shapeDrag.mode + (S.shapeDrag.handle ? ':' + S.shapeDrag.handle : ''))
: S.textDrag ? ('text:' + S.textDrag.mode)
: S.bitmapDrag ? ('bitmap:' + S.bitmapDrag.mode + (S.bitmapDrag.handle ? ':' + S.bitmapDrag.handle : ''))
: null,
selectedTextId: S.selectedTextId,
penEditId: S.penEditId,
activeLayerId: S.activeLayerId,
+19 -18
View File
@@ -8,7 +8,9 @@
'use strict'
import { S, runtime } from './state.js'
import { TEXT_FONT, allObjects, assignLayerZ, deleteSelectedShape, deleteSelectedText, layerUnits, layerUnitsDesc, renderObjects, selectUnit, sortLayersByZ, textBounds } from './objects.js'
import { allObjects, assignLayerZ, deleteSelectedShape, deleteSelectedText, layerUnits, layerUnitsDesc, otherObjectBoxes, renderObjects, selectUnit, sortLayersByZ } from './objects.js'
import { drawTextObject } from './text.js'
import { snapMove } from './snap.js'
import { boxCorners, clamp, drawRotationHandles, hitRotationHandle, rotPt, unrotPt } from './viewport.js'
import { viewScale } from './scale.js'
import { drawShape } from './tools.js'
@@ -276,8 +278,19 @@ import { isDrawableLayer } from '../vendor/layer-logic.js'
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
let nx = base.x + pos.x - drag.start.x
let ny = base.y + pos.y - drag.start.y
// 吸附到画布中线/边界与其它元素(按住 Alt 临时关掉)
if (!S._altDown && base.w > 0 && base.h > 0) {
const s = snapMove({ x: nx, y: ny, w: base.w, h: base.h }, otherObjectBoxes(layer))
nx += s.dx
ny += s.dy
S.guides = s.guides.length ? s.guides : null
} else {
S.guides = null
}
layer.x = nx
layer.y = ny
if (isDrawableLayer(layer)) layer._bounds = undefined
} else if (drag.mode === 'rotate') {
const rcx = base.x + base.w / 2, rcy = base.y + base.h / 2
@@ -454,21 +467,9 @@ export function setActiveLayer(id) {
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()
// 文字绘制统一走 text.js:预览、落层、缩略图必须是同一套度量与画法,
// 否则「量出来的选中框」和「画出来的字」会各说各话(多行/描边/底色尤其明显)
drawTextObject(ctx, obj)
}
}
+34 -6
View File
@@ -16,19 +16,19 @@ import { drawShape, setTool } from './tools.js'
import { saveSnapshot, snapshotState } from './history.js'
import { toast } from './commands.js'
import { renderOptionBar, updateLayerUI } from './events.js'
import { fontOf, newTextStyle, textBox } from './text.js'
import { drawGuides } from './snap.js'
import { isDrawableLayer } from '../vendor/layer-logic.js'
// ============ 文字图层 ============
export const TEXT_FONT = (size) => 'bold ' + size + 'px sans-serif'
/** 兼容旧调用点:TEXT_FONT(size) 返回粗体字体串;带样式的字体请用 text.js 的 fontOf(obj) */
export const TEXT_FONT = (size) => fontOf({ fontSize: size, fontWeight: 'bold' })
/** 文字包围盒:含多行、底色 padding 与描边外扩(单行时与旧实现完全一致) */
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 }
return textBox(t)
}
export function getSelectedText() {
@@ -204,6 +204,23 @@ import { isDrawableLayer } from '../vendor/layer-logic.js'
return null
}
/** 其它可见元素的包围盒(拖动吸附用):排除自己与原图底图(底图边界=画布边界,重复) */
export function otherObjectBoxes(exclude) {
const out = []
for (const unit of layerUnits()) {
const o = unit.obj
if (!o || o === exclude || o.id === 'base' || o.visible === false) continue
if (unit.kind === 'bitmap') {
if (isFinite(o.x) && isFinite(o.y) && o.w > 0 && o.h > 0) out.push({ x: o.x, y: o.y, w: o.w, h: o.h })
} else if (unit.kind === 'text') {
out.push(textBox(o))
} else {
out.push(shapeBounds(o))
}
}
return out
}
export function hitAnyObject(pos) {
for (const unit of layerUnitsDesc()) {
if (unit.kind === 'bitmap') continue
@@ -439,6 +456,8 @@ import { isDrawableLayer } from '../vendor/layer-logic.js'
for (const { kind, obj } of allObjects()) drawVectorToCanvas(kind, obj)
reorderLayerCanvas()
clearOverlay()
// 吸附参考线:拖动中才有值,松手清空。画在 overlay 层,不参与合成与导出
drawGuides(S.overlayCtx, S.guides)
if (tempShape) drawShape(S.overlayCtx, tempShape)
if (S.tool === 'pen' && S.penPath && S.penPath.pts.length) drawPenPathPreview()
// 图片放置模式优先显示放置预览
@@ -588,6 +607,9 @@ import { isDrawableLayer } from '../vendor/layer-logic.js'
input.select()
input.dataset.x = x
input.dataset.y = y
// textarea 不会自己长高:先按内容撑开,否则多行文本会挤在一行里
input.style.height = 'auto'
input.style.height = Math.max(30, input.scrollHeight + 4) + 'px'
}
export function hideTextInput() {
@@ -632,6 +654,12 @@ import { isDrawableLayer } from '../vendor/layer-logic.js'
x, y, text,
color: S.color,
fontSize: Math.max(8, S.textSize),
// 样式一次性随默认值落进对象:老对象没有这些字段,text.js 会各自回退到等价默认值
...newTextStyle({
fontWeight: S.textWeight, align: S.textAlign, lineHeight: S.textLineHeight,
strokeWidth: S.textStrokeWidth, strokeColor: S.textStrokeColor,
bgFill: S.textBgFill, bgColor: S.textBgColor
}),
opacity: 1,
visible: true,
locked: false,
@@ -0,0 +1,54 @@
/* recent-colors.js - 最近使用颜色(v1.9)
*
* 只依赖 state.js(叶子模块):tools.js 在改色时调用 rememberColor(),
* color pop 打开时 renderRecentColors() 把最近 8 个色块铺出来。
* 持久化走宿主 ctx.settings(小 KV,不放像素,符合宿主存储约定)。
*/
'use strict'
import { S, runtime } from './state.js'
const MAX = 8
const KEY = 'recentColors'
function valid(hex) {
return /^#[0-9a-f]{6}$/i.test(String(hex || ''))
}
export function loadRecentColors() {
const st = S.callbacks && S.callbacks.settings
let list = []
if (st && typeof st.get === 'function') {
try {
const got = st.get(KEY)
if (Array.isArray(got)) list = got
} catch (e) { /* 宿主 KV 不可用就当没有 */ }
}
S.recentColors = list.filter(valid).map(c => String(c).toLowerCase()).slice(0, MAX)
renderRecentColors()
}
/** 记一个颜色:去重后置顶,最多 8 个 */
export function rememberColor(hex) {
if (!valid(hex)) return
const c = String(hex).toLowerCase()
if (S.recentColors && S.recentColors[0] === c) return // 已经是最新,别每次重排
const list = [c].concat((S.recentColors || []).filter(x => x !== c))
S.recentColors = list.slice(0, MAX)
const st = S.callbacks && S.callbacks.settings
if (st && typeof st.set === 'function') {
try { st.set(KEY, S.recentColors) } catch (e) { /* 存不下就只在本次会话用 */ }
}
renderRecentColors()
}
export function renderRecentColors() {
const wrap = runtime.el && runtime.el.querySelector('.iwb-editor-recent-colors')
if (!wrap) return
const list = S.recentColors || []
wrap.innerHTML = list.map(c =>
`<button type="button" class="iwb-editor-color-panel-swatch" data-panel-color="${c}" style="background:${c}" title="最近使用 ${c}"></button>`
).join('')
wrap.hidden = !list.length
}
+94
View File
@@ -0,0 +1,94 @@
/* snap.js - 拖动吸附与参考线(v1.9)
*
* 只做两件事:算「要不要吸、吸多少」,以及把参考线画出来。
* 不碰对象的写入 —— 调用方拿到 dx/dy 自己应用到 x/y,再在 render 里画线。
* 这样位图、文字、形状三种拖动可以共用同一套吸附,不会各写一遍阈值。
*
* 吸附目标:画布中线/四边 + 其它可见元素的左/中/右与上/中/下。
* 阈值按屏幕像素给(6px),换算成图片像素后再比较 —— 否则放大图片时
* 吸附范围会跟着放大到几十像素,鼠标还没靠近就被拽走。
*/
'use strict'
import { S } from './state.js'
import { viewScale } from './scale.js'
/** 吸附触发距离(屏幕像素) */
export const SNAP_SCREEN_PX = 6
/** 参考线颜色:洋红,和选中框的橙色区分开 */
const GUIDE_COLOR = '#ff2d95'
function pushBox(targets, box) {
const x2 = box.x + box.w
const y2 = box.y + box.h
targets.x.push(box.x, box.x + box.w / 2, x2)
targets.y.push(box.y, box.y + box.h / 2, y2)
}
/** 在候选线里找「离得最近且不超过阈值」的那条,返回需要平移的量 */
function nearest(targets, sources, tol, axis) {
let best = null
for (let i = 0; i < targets.length; i++) {
for (let j = 0; j < sources.length; j++) {
const delta = targets[i] - sources[j]
const abs = Math.abs(delta)
if (abs > tol) continue
if (!best || abs < Math.abs(best.delta)) best = { delta: delta, at: targets[i], axis: axis }
}
}
return best
}
/**
* 计算吸附位移。
* @param {{x:number,y:number,w:number,h:number}} box 被拖元素的包围盒(已按指针位移算好,未吸附)
* @param {Array<{x:number,y:number,w:number,h:number}>} others 其它元素的包围盒
* @returns {{dx:number, dy:number, guides:Array}}
*/
export function snapMove(box, others) {
const tol = SNAP_SCREEN_PX / Math.max(0.02, viewScale())
const targets = { x: [0, S.imgW / 2, S.imgW], y: [0, S.imgH / 2, S.imgH] }
for (const o of others || []) {
if (!o || !isFinite(o.x) || !isFinite(o.y)) continue
pushBox(targets, o)
}
const sourcesX = [box.x, box.x + box.w / 2, box.x + box.w]
const sourcesY = [box.y, box.y + box.h / 2, box.y + box.h]
const gx = nearest(targets.x, sourcesX, tol, 'x')
const gy = nearest(targets.y, sourcesY, tol, 'y')
const guides = []
if (gx) guides.push(gx)
if (gy) guides.push(gy)
return { dx: gx ? gx.delta : 0, dy: gy ? gy.delta : 0, guides: guides }
}
/** 画参考线(贯穿整个画布 + overlay 外扩区,拖动时一眼看到对齐到哪) */
export function drawGuides(ctx, guides) {
if (!guides || !guides.length || !ctx) return
const scale = viewScale()
const pad = S.overlayPad || 0
ctx.save()
ctx.strokeStyle = GUIDE_COLOR
ctx.lineWidth = 1 / Math.max(0.02, scale)
ctx.setLineDash([6 / Math.max(0.02, scale), 4 / Math.max(0.02, scale)])
for (const g of guides) {
ctx.beginPath()
if (g.axis === 'x') {
ctx.moveTo(g.at, -pad)
ctx.lineTo(g.at, S.imgH + pad)
} else {
ctx.moveTo(-pad, g.at)
ctx.lineTo(S.imgW + pad, g.at)
}
ctx.stroke()
}
ctx.setLineDash([])
ctx.restore()
}
export function clearGuides() {
if (!S.guides) return
S.guides = null
}
+12
View File
@@ -38,7 +38,18 @@
// v1.2 工具参数解耦:形状线宽与文字字号不再借用画笔粗细,
// 否则「调细画笔」会顺手把所有形状的描边一起改掉。
shapeLineWidth: 3, // 矩形/圆形/箭头/钢笔的描边粗细
shapeRadius: 0, // 矩形圆角半径 px(v1.9,仅 rect 有意义)
textSize: 32, // 新建文字的字号 px
// ---- v1.9 文字样式:这套是「新建文字」的默认值,每段文字自己存一份 ----
textWeight: 'bold', // bold | normal | 900
textAlign: 'left', // left | center | right(多行时各行按块宽对齐)
textLineHeight: 1.25, // 行高倍数(1.25 = 老版单行高度,勿随意改)
textStrokeWidth: 0, // 描边宽度 px,0 = 无描边
textStrokeColor: '#ffffff',
textBgFill: false, // 底色块
textBgColor: '#000000',
// 最近使用颜色(最多 8 个,存 ctx.settings,跨会话保留)
recentColors: [],
// 图层系统
layers: [], // 位图图层数组 [{ id, name, canvas, ctx, opacity, visible, z }]
activeLayerId: null, // 当前活跃位图图层 ID(画笔/橡皮操作目标)
@@ -113,6 +124,7 @@
exportOptions: null, // { preset, format, bg, maxKB, size },来自 ctx.settings
interaction: 'idle', // 轻量交互状态机:idle | marquee | lasso | placing | cropping
renderAll: null, // 由 index.js 注入的统一重绘出口
guides: null, // 拖动吸附参考线(图片坐标,松手清空):[{axis:'x'|'y', at, from, to}]
lastExport: null // 观测口:{ bytes, width, height, format, preset }
}
+155
View File
@@ -0,0 +1,155 @@
/* text.js - 文字的字体串、度量与绘制(v1.9)
*
* 为什么单独一个模块:文字要在两处画 —— 落层(layers.js#drawVectorToCanvas)与
* 预览/度量(objects.js)。两边各写一遍必然出现「量出来的框和画出来的字不一样」。
* 这里做成零依赖叶子模块(不 import 任何编辑器模块),objects.js 与 layers.js
* 都只往下依赖它,不会形成循环 import(esbuild 打成 IIFE 时循环 import 会拿到 undefined)。
*
* 坐标语义(与 v1.8 之前保持一致,勿随意改动):
* t.x / t.y 是「文字块」左上角;底色 padding 与描边从这一点向内/外扩展。
* 单行 + 无底色 + 无描边时,textBox() 与老版 textBounds() 完全相等(w=文字宽,h=fontSize×1.25)。
*/
'use strict'
/** 默认行高倍数:必须等于老版的 fontSize×1.25,否则单行文字的选中框会变高 */
export const TEXT_LINE_HEIGHT = 1.25
/** 底色块相对字号的 padding 系数 */
const BG_PAD_RATIO = 0.3
let _measureCtx = null
/** 度量用的离屏 ctx:不依赖编辑器 DOM 是否已建好,避免 textBounds 在早期调用时抛错 */
function measureCtx() {
if (!_measureCtx) {
const c = document.createElement('canvas')
c.width = 8
c.height = 8
_measureCtx = c.getContext('2d')
}
return _measureCtx
}
/** 字重:'bold' | 'normal' | '900' …(默认粗体,与老版一致) */
export function weightOf(t) {
const w = t && t.fontWeight
return w == null || w === '' ? 'bold' : String(w)
}
export function fontOf(t) {
const size = Math.max(4, Number(t && t.fontSize) || 32)
return weightOf(t) + ' ' + size + 'px sans-serif'
}
/** 文字的排布度量:分行、每行宽度、行高、底色 padding、描边宽度 */
export function textMetrics(t) {
const ctx = measureCtx()
const font = fontOf(t)
ctx.font = font
const raw = (t && t.text) == null ? '' : String(t.text)
const lines = raw.split('\n')
const widths = lines.map(line => ctx.measureText(line).width)
const size = Math.max(4, Number(t && t.fontSize) || 32)
const lh = size * (Number(t && t.lineHeight) || TEXT_LINE_HEIGHT)
const w = lines.length ? Math.max.apply(null, widths) : 0
const pad = t && t.bgFill ? Math.round(size * BG_PAD_RATIO) : 0
const sw = Math.max(0, Number(t && t.strokeWidth) || 0)
return { lines, widths, w, h: lh * lines.length, lh, pad, sw, font, size }
}
/** 包围盒(图片坐标):含底色 padding 与描边向外扩出的一半 */
export function textBox(t) {
const m = textMetrics(t)
const half = m.sw / 2
return {
x: t.x - half,
y: t.y - half,
w: Math.max(m.w, 2) + m.pad * 2 + m.sw,
h: Math.max(m.h, 1) + m.pad * 2 + m.sw
}
}
function alignOf(t) {
const a = t && t.align
return a === 'center' || a === 'right' ? a : 'left'
}
/**
* 画一段文字(含底色块、描边、多行、旋转)。
* 底色块与描边都按「块」来画:底色覆盖整块,描边沿字形外沿。
*/
export function drawTextObject(ctx, t) {
const m = textMetrics(t)
ctx.save()
ctx.textBaseline = 'top'
ctx.globalAlpha = t.opacity != null ? t.opacity : 1
const b = textBox(t)
const rot = t.rotation || 0
if (rot) {
const cx = b.x + b.w / 2
const cy = b.y + b.h / 2
ctx.translate(cx, cy)
ctx.rotate(rot * Math.PI / 180)
ctx.translate(-cx, -cy)
}
ctx.font = m.font
const align = alignOf(t)
const boxW = m.w + m.pad * 2
// 底色块:先于文字画,圆角按字号比例给一点(纯直角贴小字会很硬)
if (t.bgFill) {
const r = Math.min(m.pad + 2, Math.min(boxW, m.h + m.pad * 2) / 2)
ctx.globalAlpha = (t.opacity != null ? t.opacity : 1) * (t.bgAlpha == null ? 0.55 : t.bgAlpha)
ctx.fillStyle = t.bgColor || '#000000'
const bx = t.x, by = t.y
const bw = boxW, bh = m.h + m.pad * 2
ctx.beginPath()
if (typeof ctx.roundRect === 'function') {
ctx.roundRect(bx, by, bw, bh, r)
} else {
ctx.moveTo(bx + r, by)
ctx.arcTo(bx + bw, by, bx + bw, by + bh, r)
ctx.arcTo(bx + bw, by + bh, bx, by + bh, r)
ctx.arcTo(bx, by + bh, bx, by, r)
ctx.arcTo(bx, by, bx + bw, by, r)
ctx.closePath()
}
ctx.fill()
ctx.globalAlpha = (t.opacity != null ? t.opacity : 1)
}
// 对齐以「块内可用宽度(不含 padding)」为基准:多行时各行按这个宽度对齐
ctx.textAlign = align
const left = t.x + m.pad
const ox = align === 'center' ? left + m.w / 2 : align === 'right' ? left + m.w : left
ctx.lineJoin = 'round'
ctx.miterLimit = 2
for (let i = 0; i < m.lines.length; i++) {
const y = t.y + m.pad + i * m.lh
if (m.sw > 0) {
ctx.lineWidth = m.sw
ctx.strokeStyle = t.strokeColor || '#ffffff'
ctx.strokeText(m.lines[i], ox, y)
}
ctx.fillStyle = t.color || '#ff4444'
ctx.fillText(m.lines[i], ox, y)
}
ctx.restore()
}
/** 从默认样式造一段文字的字段(新建文字 / 老对象补默认值共用) */
export function newTextStyle(src) {
const s = src || {}
return {
fontWeight: weightOf(s),
align: alignOf(s),
lineHeight: Number(s.lineHeight) || TEXT_LINE_HEIGHT,
strokeWidth: Math.max(0, Number(s.strokeWidth) || 0),
strokeColor: s.strokeColor || '#ffffff',
bgFill: !!s.bgFill,
bgColor: s.bgColor || '#000000',
bgAlpha: s.bgAlpha == null ? 0.55 : Number(s.bgAlpha)
}
}
+32 -2
View File
@@ -18,6 +18,7 @@ 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'
// ============ 绘制工具 ============
@@ -160,6 +161,24 @@ import { hexToRgb, rgbToHex } from '../vendor/image-math.js'
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()
}
/** 按形状对象绘制(矩形/箭头),预览与最终渲染共用 */
export function drawShape(ctx, s) {
ctx.save()
@@ -181,8 +200,16 @@ import { hexToRgb, rgbToHex } from '../vendor/image-math.js'
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)
const radius = roundedRadius(s, rw, rh)
if (radius > 0) {
ctx.beginPath()
roundRectPath(ctx, rx, ry, rw, rh, radius)
if (s.fill) { ctx.fillStyle = s.color; ctx.fill() }
ctx.stroke()
} else {
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)
@@ -380,6 +407,9 @@ import { hexToRgb, rgbToHex } from '../vendor/image-math.js'
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) {