Files
iwb-plugins-desktop/image-annotate/plugin/editor/effects.js
T
qiqi 3819048e54 feat(image-annotate): v1.8.0 快速效果加参数(马赛克块大小 / 柔化半径 / 其余强度)
v1.4 的六个效果都是一键定死强度:马赛克在 800px 图上固定 13px 块挡不住手机号,
柔化固定 1.6px 小图上几乎看不出。现在每个效果都带参数,点完还能继续拖。

参数模型:
- 百分比类(反白/灰度/增强/高对比):强度 0~100%,走 invert()/grayscale() 原生比例,
  其余按 k 插值(高对比 = grayscale(k) contrast(1+1.4k))
- 物理量类:柔化半径 0~16px、马赛克块大小 2~96px,默认值按短边缩放

关键设计:效果不能叠加在自己的结果上。
点效果时把目标层像素备份进 S.fx.source,拖滑杆一律「先还原 source 再按新参数渲染」。
否则「马赛克 12 → 48 → 12」会做三次重采样,块越来越碎且不可逆。

交互约定:
- 一次效果 = 一条撤销(点效果时快照,拖滑杆不再拍)
- 同效果再点 = 回默认值,不再糊一层
- 切到别的层滑杆置灰(源属于旧层),切回自动恢复
- 当前生效效果描橙边;拖滑杆不重建图层面板(否则每帧 innerHTML 会闪)

顺带修了两处既有缺陷:
- .iwb-editor-fx-target 标签从来没被更新过,一直显示「原图」——现在跟随目标层
- 柔化默认过弱(1.6px / 800px 图)——系数改 400、下限 1.2

验证:harness 139 项全通(新增 6 项,含「12→48→12 像素指纹一致」的叠加检测)、
validate 9/9、产物 341608 B。
2026-11-08 17:06:56 +08:00

329 lines
13 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.
/* effects.js - 侧栏「快速效果」(v1.4,v1.8 加可调参数)
*
* 作用对象只有一个:当前位图图层(侧栏标题后面实时显示层名)。
* 全部走 canvas 2D 的 ctx.filter / 缩放重采样,不引入依赖、不动矢量层、
* 不改图层几何,因此对「原图」这种带 locked 标记的层也安全(效果不是画笔)。
*
* 撤销:应用前 saveSnapshot()。base 与画笔层走像素快照(putImageData),
* 天然可回退;导入图片层走 image/sourceCanvas 重绘,原地改像素会被下一次
* 重绘冲掉,所以先按 PS「栅格化」的做法落一个普通位图副本(原层隐藏)。
*
* v1.8 可调参数的关键设计:**效果不能叠加在自身结果上**。
* 点效果时把目标层当时的像素备份进 S.fx.source,之后拖滑杆一律「先还原 source
* 再按新参数渲染」。否则「马赛克 12px → 40px → 12px」会变成三次采样、块越来
* 越碎且不可逆。历史粒度也因此干净:点效果拍一次快照,拖滑杆不再拍。
*/
'use strict'
import { S, runtime } from './state.js'
import { saveSnapshot } from './history.js'
import { createLayerCanvas, getActiveLayer, renderLayerPanel, reorderLayerCanvas, updateLayerCanvasStyles } from './layers.js'
import { layerUnits } from './objects.js'
import { needsPixelSnapshot } from '../vendor/layer-logic.js'
import { toast } from './commands.js'
const SOFT_MIN = 1.2
const SOFT_MAX = 8
function softRadius(canvas) {
// 默认半径跟短边走:800px 图 ≈2px(v1.4 是 1.6px,小图上几乎看不出模糊,
// 现在有了滑杆可自己拉,但默认值也要先看得出效果)
const side = Math.min(canvas.width || 0, canvas.height || 0)
return Math.max(SOFT_MIN, Math.min(SOFT_MAX, Math.round(side / 400 * 10) / 10))
}
function mosaicBlock(canvas) {
const side = Math.min(canvas.width || 0, canvas.height || 0)
return Math.max(6, Math.round(side / 60))
}
/**
* 效果表。参数语义分两类:
* unit '%' → 强度 0~100,0 等于不处理(invert/grayscale 原生支持比例)
* unit 'px' → 物理量(马赛克块边长 / 模糊半径),默认值按图短边缩放
* def 是函数:px 类要拿到 canvas 才能算默认值。
*/
export const QUICK_EFFECTS = {
invert: {
label: '反白', hint: '反相:明暗翻转,白底变黑底',
param: '强度', unit: '%', min: 0, max: 100, step: 1, def: () => 100,
render: (canvas, v) => { if (v > 0) filterCanvas(canvas, 'invert(' + (v / 100) + ')') }
},
gray: {
label: '灰度', hint: '去色,保留明暗层次',
param: '强度', unit: '%', min: 0, max: 100, step: 1, def: () => 100,
render: (canvas, v) => { if (v > 0) filterCanvas(canvas, 'grayscale(' + (v / 100) + ')') }
},
boost: {
label: '增强', hint: '提亮并略加对比,适合发灰的截图',
param: '强度', unit: '%', min: 0, max: 100, step: 1, def: () => 100,
render: (canvas, v) => {
if (v <= 0) return
const k = v / 100
filterCanvas(canvas, 'brightness(' + (1 + 0.12 * k).toFixed(3) + ') contrast(' + (1 + 0.1 * k).toFixed(3) + ') saturate(' + (1 + 0.06 * k).toFixed(3) + ')')
}
},
contrast: {
label: '高对比', hint: '压成黑白硬调,突出主体',
param: '强度', unit: '%', min: 0, max: 100, step: 1, def: () => 100,
render: (canvas, v) => {
if (v <= 0) return
const k = v / 100
filterCanvas(canvas, 'grayscale(' + k.toFixed(3) + ') contrast(' + (1 + 1.4 * k).toFixed(3) + ')')
}
},
soft: {
label: '柔化', hint: '模糊,弱化背景',
param: '半径', unit: 'px', min: 0, max: 16, step: 0.5, def: (canvas) => softRadius(canvas),
render: (canvas, v) => { if (v > 0) filterCanvas(canvas, 'blur(' + v + 'px)') }
},
mosaic: {
label: '马赛克', hint: '像素化,用于打码手机号/地址等隐私信息',
param: '块大小', unit: 'px', min: 2, max: 96, step: 1, def: (canvas) => mosaicBlock(canvas),
render: (canvas, v) => { if (v > 1) pixelateCanvas(canvas, v) }
}
}
/** 效果目标:当前活跃位图图层;没有就退回「原图」 */
export function effectTarget() {
const active = getActiveLayer()
if (active) return active
return S.layers.find(l => l.id === 'base') || null
}
/** 用 ctx.filter 把画布自身重绘一遍(临时画布中转,避免自绘自的采样问题) */
function filterCanvas(canvas, css) {
const w = canvas.width, h = canvas.height
if (!w || !h || !css) return
const tmp = document.createElement('canvas')
tmp.width = w
tmp.height = h
const tctx = tmp.getContext('2d')
tctx.filter = css
tctx.drawImage(canvas, 0, 0)
const ctx = canvas.getContext('2d')
ctx.save()
// 图层 ctx 平时带着视图变换,重绘必须回到设备像素坐标系
ctx.setTransform(1, 0, 0, 1, 0, 0)
ctx.globalAlpha = 1
ctx.globalCompositeOperation = 'copy' // copy:连透明像素一起替换,不留旧内容
ctx.filter = 'none'
ctx.drawImage(tmp, 0, 0)
ctx.restore()
}
/** 马赛克:缩到 1/block 再关掉平滑放大,比逐像素 getImageData 快一个量级 */
function pixelateCanvas(canvas, block) {
const w = canvas.width, h = canvas.height
if (!w || !h) return
const b = Math.max(2, block)
const sw = Math.max(1, Math.round(w / b))
const sh = Math.max(1, Math.round(h / b))
const tmp = document.createElement('canvas')
tmp.width = sw
tmp.height = sh
const tctx = tmp.getContext('2d')
tctx.imageSmoothingEnabled = true
tctx.drawImage(canvas, 0, 0, sw, sh)
const ctx = canvas.getContext('2d')
ctx.save()
ctx.setTransform(1, 0, 0, 1, 0, 0)
ctx.globalAlpha = 1
ctx.globalCompositeOperation = 'copy'
ctx.imageSmoothingEnabled = false
ctx.filter = 'none'
ctx.drawImage(tmp, 0, 0, w, h)
ctx.restore()
}
/** 目标层像素的独立副本(同尺寸),作为「可反复重调」的基准 */
function snapshotCanvas(canvas) {
const c = document.createElement('canvas')
c.width = canvas.width
c.height = canvas.height
const ctx = c.getContext('2d')
ctx.drawImage(canvas, 0, 0)
return c
}
/**
* 把「导入图片层」栅格化成普通位图,插在它上面一层。
* 只拷当前 canvas 的可见结果(已含旋转/缩放),所以视觉不变。
* 原层隐藏而不删除:撤销时快照里有它的 visible,能原样恢复。
*/
function rasterizeLayer(layer) {
const canvas = createLayerCanvas()
const ctx = canvas.getContext('2d', { willReadFrequently: true })
ctx.clearRect(0, 0, S.imgW, S.imgH)
ctx.drawImage(layer.canvas, 0, 0)
// z 取「原层 → 上一层」的中点,保证副本紧贴在原层上方,不会窜到别的标注之上
const units = layerUnits()
const i = units.findIndex(u => u.kind === 'bitmap' && u.obj === layer)
const baseZ = layer.z || 0
const nextZ = (i >= 0 && units[i + 1]) ? (units[i + 1].obj.z || 0) : baseZ + 1
const z = nextZ > baseZ ? (baseZ + nextZ) / 2 : baseZ + 0.5
const clone = {
id: 'fx' + Date.now() + Math.floor(Math.random() * 1000),
name: layer.name + ' · 效果',
canvas,
ctx,
opacity: layer.opacity == null ? 1 : layer.opacity,
visible: true,
locked: false,
x: 0, y: 0, w: S.imgW, h: S.imgH,
rotation: 0,
z
}
S.layers.push(clone)
layer.visible = false
if (S.selectedLayerId === layer.id) S.selectedLayerId = clone.id
S.activeLayerId = clone.id
reorderLayerCanvas()
updateLayerCanvasStyles()
renderLayerPanel()
return clone
}
/** 先还原基准像素,再按参数渲染一次 —— 所有重调都走这里 */
function renderFromSource(target, key, value) {
const st = S.fx
const fx = QUICK_EFFECTS[key]
if (!st.source || !fx) return
const ctx = target.canvas.getContext('2d')
ctx.save()
ctx.setTransform(1, 0, 0, 1, 0, 0)
ctx.globalAlpha = 1
ctx.globalCompositeOperation = 'copy'
ctx.filter = 'none'
ctx.imageSmoothingEnabled = true
ctx.drawImage(st.source, 0, 0)
ctx.restore()
fx.render(target.canvas, value)
// 像素变了:包围盒要重算,吸管合成缓存要作废
target._bounds = undefined
S.pickerComposite = null
}
/** 数值展示:px 保留到 0.5(柔化),百分比取整 */
function fmtValue(fx, v) {
if (fx.unit === 'px') return (Math.round(v * 10) / 10) + ' px'
return Math.round(v) + '%'
}
/**
* 刷新侧栏「强度」这一条:滑杆范围随效果切换,目标层对不上时置灰。
* 切图层后源属于旧层,此时拖动会把旧像素写进新层 —— 所以必须靠 layerId 拦住。
* 切回原层自动恢复可用(源还在)。
*/
export function renderFxPanel() {
if (!runtime.el) return
const adv = runtime.el.querySelector('.iwb-editor-fx-adj')
if (!adv) return
const range = adv.querySelector('.iwb-editor-fx-range')
const nameEl = adv.querySelector('.iwb-editor-fx-adj-name')
const valEl = adv.querySelector('.iwb-editor-fx-adj-val')
const targetEl = runtime.el.querySelector('.iwb-editor-fx-target')
const layer = effectTarget()
// 当前生效的效果按钮高亮:面板是静态 DOM,只同步类名,不重建
const activeKey = S.fx.source ? S.fx.key : null
runtime.el.querySelectorAll('[data-fx]').forEach(btn => {
btn.classList.toggle('is-active', Boolean(activeKey) && btn.dataset.fx === activeKey)
})
if (targetEl) {
const name = layer ? layer.name : '无图层'
targetEl.textContent = name
targetEl.title = layer ? '效果作用于「' + name + '」' : '没有可处理的位图图层'
}
const st = S.fx
const fx = st.source ? QUICK_EFFECTS[st.key] : null
if (!fx || !range) {
adv.classList.add('iwb-editor-fx-adj-off')
if (nameEl) nameEl.textContent = '强度'
if (valEl) valEl.textContent = '—'
if (range) { range.disabled = true; range.value = '0' }
return
}
const usable = Boolean(layer && st.layerId === layer.id)
adv.classList.toggle('iwb-editor-fx-adj-off', !usable)
if (nameEl) nameEl.textContent = fx.label + ' · ' + fx.param
range.min = String(fx.min)
range.max = String(fx.max)
range.step = String(fx.step)
range.disabled = !usable
if (usable) range.value = String(st.value)
if (valEl) {
valEl.textContent = fmtValue(fx, st.value)
valEl.title = usable ? '' : '效果作用在「' + (S.layers.find(l => l.id === st.layerId) || {}).name + '」,切回该层可继续调整'
}
}
/** 唯一入口:应用一个效果(同层同效果再点 = 重置回默认参数,不叠加) */
export function applyQuickEffect(key) {
const fx = QUICK_EFFECTS[key]
if (!fx) return false
const layer = effectTarget()
if (!layer) { toast('没有可处理的图层'); return false }
if (layer.visible === false) {
toast('「' + layer.name + '」已隐藏,先显示再应用效果')
return false
}
let target = layer
if (!needsPixelSnapshot(layer)) target = rasterizeLayer(layer)
if (!target) { toast('栅格化失败,效果未应用'); return false }
const st = S.fx
// 同一层 + 同一效果:用户是在「回默认值」,不是要再糊一层
if (st.source && st.layerId === target.id && st.key === key) {
st.value = fx.def(target.canvas)
renderFromSource(target, key, st.value)
if (S.renderAll) S.renderAll()
toast('「' + fx.label + '」已重置为 ' + fmtValue(fx, st.value), 'success')
return true
}
saveSnapshot('效果:' + fx.label)
// 基准必须是「应用前」的像素:saveSnapshot 只写历史,不改画布,所以这里拍
S.fx = { key, layerId: target.id, source: snapshotCanvas(target.canvas), value: fx.def(target.canvas) }
renderFromSource(target, key, S.fx.value)
if (S.renderAll) S.renderAll()
toast('已应用「' + fx.label + '」' + fmtValue(fx, S.fx.value) + ' 到 ' + target.name + ' · 可拖强度微调', 'success')
return true
}
/**
* 拖动强度滑杆。不拍快照(历史粒度 = 一次效果操作),也不重建图层面板
* (拖动中每帧 innerHTML 会闪,缩略图交给松开后的 renderAll 刷新)。
*/
export function setEffectValue(value) {
const st = S.fx
if (!st.source) return false
const fx = QUICK_EFFECTS[st.key]
if (!fx) return false
const target = S.layers.find(l => l.id === st.layerId)
if (!target) return false
const layer = effectTarget()
// 目标层已切换:源像素属于别的层,拒绝写入
if (!layer || layer.id !== st.layerId) return false
const v = Math.min(fx.max, Math.max(fx.min, Number(value) || 0))
st.value = v
renderFromSource(target, st.key, v)
if (runtime.el) {
const valEl = runtime.el.querySelector('.iwb-editor-fx-adj-val')
if (valEl) valEl.textContent = fmtValue(fx, v)
}
return true
}