banner
banner
banner
NEWS LETTER

Taro 图片裁剪:八向拖拽框与 Canvas 导出

Scroll down

自由裁剪页解决的是「裁剪框大小不固定」的框选需求:8 个控制点分别对应四角和四边中点,既能单独拖某一条边,也能整体挪位置。
整条链路是:选图拿临时路径 → getImageInfo 读原图尺寸 → 等比算出显示尺寸 → 分层叠图 → 拖拽改 left / top / boxWidth / boxHeight → Canvas 按 dpr 导出 → 存相册。
真正容易错的只有两件事:scale 这个换算基准不能跨坐标系乱用,dpr 只允许乘一次。
下文先交代入口页的参数契约,再逐段看拖拽与导出,最后收几个原稿里跑不起来的写法。

背景

代码在 pages/img/ 目录:imgClip.tsx 是本页,chooseImg.tsx 是三个裁剪页的统一入口,imgClipMovalview.tsx(比例裁剪)和 nineSquareGridClip.tsx(九宫格)是另外两版实现,公共 canvas 工具在 utils/canvas.tsx,控制点样式在 styles/index.scss 的 .point-*。

本页要做的事:用户从大图里框出任意矩形区域。因为框大小不固定,需求自然拆成两套手势——「8 个控制点拖拽」负责改某一条边,「高亮图层拖拽」负责整体平移,两者互不干扰。

四个尺寸先分清,后面所有换算问题都出在这里:

量 来源 用途
原图尺寸 width / height getImageInfo 换算基准、导出上限
显示尺寸 imgCurWidth / imgCurHeight 等比缩放到整图可见 触摸与拖拽的唯一坐标系
裁剪框 left / top / boxWidth / boxHeight 用户拖拽 与显示尺寸同一坐标系
画布尺寸 canvas.width / height 裁剪尺寸 ÷ scale × dpr 只影响清晰度,不影响布局

整个页面只有一个换算基准:

1
2
const scale = imgCurWidth / res.width   // 显示尺寸 ÷ 原图尺寸
// 显示坐标 × (1 / scale) = 原图坐标

入口页的参数契约

进本页之前,用户先经过 chooseImg.tsx。它没有裁剪逻辑,只是三个裁剪页的统一入口,因此也是整套裁剪能力的参数契约中心:自由裁剪 / 比例裁剪 / 九宫格三页参数各不相同,入口统一后页面之间不需要互相知道对方存在。

入口页维护 6 种裁剪比例,选中态用绿色背景标记:

1
2
3
4
5
6
7
8
9
const imgRatioOptions = [[1, 1], [2, 3], [2, 1], [3, 2], [4, 3], [16, 9]]

const [imgRatio, setImgRatio] = useState([1, 1])
const [selectedIndex, setSelectedIndex] = useState(0)

const handleRatio = (index: number) => {
setImgRatio(imgRatioOptions[index])
setSelectedIndex(index)
}

三个入口卡片共用一个 getLocationImage(num),num 决定跳哪一页、带哪些参数:

num 目标页 query 说明
0 ./imgClip imgUrl 本页,只需要图片地址
1 ./imgClipMovalview imgUrl + imgRatio 比例裁剪,多一个 [宽, 高] 数组
2 ./nineSquareGridClip imgUrl 九宫格,比例固定 1:1,不传
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
const getLocationImage = (num: number) => {
// 非法值在入口同步拦截,不要拖到异步回调里
if (num < 0 || num > 2) {
showToast({ title: '裁剪类型不合法', icon: 'none' })
return
}

chooseImage({
count: 1,
sizeType: ['original', 'compressed'],
sourceType: ['album', 'camera'],
success: (res) => {
const imgUrl = encodeURIComponent(res.tempFilePaths[0])
if (num === 0) {
navigateTo({ url: `./imgClip?imgUrl=${imgUrl}` })
} else if (num === 1) {
const ratio = encodeURIComponent(JSON.stringify(imgRatio)) // 数组必须序列化
navigateTo({ url: `./imgClipMovalview?imgUrl=${imgUrl}&imgRatio=${ratio}` })
} else {
navigateTo({ url: `./nineSquareGridClip?imgUrl=${imgUrl}` })
}
},
fail: () => {
// 用户取消选图是正常操作,不是异常
showToast({ title: '未选择图片', icon: 'none' })
},
})
}

原稿问题:success / fail 回调里写 throw new Error(...)。这两个回调由框架异步触发,外层没有任何 try/catch,throw 出去只会变成一条未捕获异常日志,既不中断流程也不提示用户;fail 里抛错还把「用户取消选图」当成了错误。正确写法是提示后 return,非法 num 在函数入口同步拦截。

原稿问题:imgRatio 用 JSON.stringify 序列化进了 query,但反序列化那一步没有代码。接收端必须显式 JSON.parse,否则拿到的是字符串 "[2,3]",参与除法会得到 NaN。

接收端(本页)只要图片地址,顺手把编码解掉:

1
2
3
useLoad((options) => {
setImgUrlState(decodeURIComponent(options.imgUrl || ''))
})

实现

1. 分层结构

页面一共叠了 5 层,用 z-index 严格分层:

层级 内容 作用
底层 <Image> 原图(opacity-50) 暗底图,裁剪时变半透明
z-20 <Image> 原图 + clipPath: polygon(...) 裁剪框内的清晰图,承接整体拖拽
z-30 8 个 .point 控制点 单角 / 单边拖拽
z-30 .point-centerH / .point-centerV 四边中点拖拽
z-30 预览层(含 <Canvas>) 点「预览」后显示裁剪结果

『同一张图叠两层,下层压暗、上层用 clip-path 挖出裁剪框』——这是裁剪 UI 最经典的画法,不需要真的去裁剪 DOM。

2. 关键状态

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
const [imgInfo, setImgInfo] = useState({
width: 0, height: 0, // 原图真实尺寸
imgCurWidth: 0, imgCurHeight: 0, // 等比缩放到屏幕后的显示尺寸
scale: 0, // imgCurWidth / width
dpr: 1, // 像素比,>=3 时压成 1(安卓兼容)
})

const [clipPoints, setclipPoints] = useState({
left: 0, top: 0,
boxWidth: 300, boxHeight: 300,
centerH: 0, // 裁剪框水平中点 x
centerV: 0, // 裁剪框垂直中点 y
})

const [initPoints, setInitPoints] = useState({
leftTop: { x: 100, y: 100 }, leftBottom: { x: 100, y: 400 },
rightTop: { x: 500, y: 100 }, rightBottom: { x: 500, y: 400 },
move: { x: 0, y: 0 }, // 整体拖拽的起点
})

3. 初始化:把原图尺寸换算成显示尺寸

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
useEffect(() => {
const fetchImageInfo = () => {
const { screenWidth, pixelRatio } = getWindowInfo()
const imgCurWidth = screenWidth
// 安卓上 dpr 过高会撑爆 canvas buffer,>=3 时压成 1
const dpr = pixelRatio >= 3 ? 1 : pixelRatio

getImageInfo({
src: imgUrlState,
success: (res) => {
const scale = imgCurWidth / res.width
const imgCurHeight = Math.floor(res.height * scale)
setImgInfo({ width: res.width, height: res.height, imgCurWidth, imgCurHeight, scale, dpr })

// 裁剪框初始 300×300(原图单位),居中
const width = 300 * scale
const height = 300 * scale
const left = (imgCurWidth - width) / 2
const top = (imgCurHeight - height) / 2
setclipPoints({
left, top, boxWidth: width, boxHeight: height,
centerH: left + width / 2 - 13 / 2, // 13 / 12 = 控制点自身尺寸的补偿值
centerV: top + height / 2 - 12 / 2,
})
},
fail: (err) => {
showToast({ title: err.errMsg || '读取图片失败', icon: 'none' })
},
})
}
fetchImageInfo()
}, [imgUrlState])

『scale 是整个页面的换算基准』:显示坐标 × (1/scale) = 原图坐标。后面 Canvas 导出全靠它。

4. 控制点拖拽

统一用一个 handlePointMove(e, flag) 处理 8 个方向,靠 flag 判断改哪条边。用「增量位移 + 函数式更新」:moveX 是相对上一次 touchmove 的差值,每次结束后把该方向的起点刷新为当前触点,手指滑出屏幕再回来也不会跳变。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
const MIN_BOX = 100

const handlePointMove = (e, flag: string) => {
e.preventDefault() // 低端安卓不加会导致 touchend 不触发
e.stopPropagation()

const { clientX, clientY } = e.touches[0]
const moveX = clientX - initPoints[flag].x
const moveY = clientY - initPoints[flag].y
const { imgCurWidth, imgCurHeight } = imgInfo

setclipPoints((prev) => {
// 全部从 prev 取,避免高频移动时读到过期闭包
const { left, top, boxWidth, boxHeight } = prev
let _left = left
let _top = top
let _boxWidth = boxWidth
let _boxHeight = boxHeight

// 左边三向:左上、左下、左中
if (flag === 'leftTop' || flag === 'leftBottom' || flag === 'centerLeft') {
_left = Math.max(0, left + moveX)
_boxWidth = _left <= 0
? Math.max(boxWidth, MIN_BOX) // 贴边后不再继续缩
: Math.max(boxWidth - moveX, MIN_BOX)
}
// 上边三向
if (flag === 'leftTop' || flag === 'rightTop' || flag === 'centerTop') {
_top = Math.max(0, top + moveY)
_boxHeight = _top <= 0
? Math.max(boxHeight, MIN_BOX)
: Math.max(boxHeight - moveY, MIN_BOX)
}
// 下边三向:只看底边能往下挪多少,再夹最小高度
if (flag === 'leftBottom' || flag === 'rightBottom' || flag === 'centerBottom') {
_boxHeight = Math.max(MIN_BOX, Math.min(boxHeight + moveY, imgCurHeight - top))
}
// 右边三向
if (flag === 'rightTop' || flag === 'rightBottom' || flag === 'centerRight') {
_boxWidth = Math.max(MIN_BOX, Math.min(boxWidth + moveX, imgCurWidth - left))
}

return {
left: _left,
top: _top,
boxWidth: _boxWidth,
boxHeight: _boxHeight,
centerH: _left + _boxWidth / 2 - 13 / 2,
centerV: _top + _boxHeight / 2 - 12 / 2,
}
})

setInitPoints((prev) => ({ ...prev, [flag]: { x: clientX, y: clientY } }))
}

原稿问题:_boxHeight = Math.max(_boxHeight, 100) 这类写的其实是自己,if (_top >= ...) _boxHeight = _boxHeight 更是空语句,下边 / 右边两个分支等于没做夹取。改成「先算能挪多少,再夹最小尺寸与容器边界」。

5. 整体拖拽

整体拖拽就是改 left / top 然后夹边界。原稿这段直接用了 clientX / clientY / boxWidth / boxHeight 四个从未声明的变量,这里补齐出处:触点来自 e.touches[0],框尺寸来自 prev。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
const handleImageMove = (e) => {
e.preventDefault()
e.stopPropagation()

const { clientX, clientY } = e.touches[0] // 触点来自事件
const { imgCurWidth, imgCurHeight } = imgInfo // 容器边界来自图片显示尺寸
const moveX = clientX - initPoints.move.x
const moveY = clientY - initPoints.move.y

setclipPoints((prev) => {
const { boxWidth, boxHeight } = prev // 框尺寸来自上一次状态
const newLeft = Math.max(0, Math.min(prev.left + moveX, imgCurWidth - boxWidth))
const newTop = Math.max(0, Math.min(prev.top + moveY, imgCurHeight - boxHeight))
return {
...prev,
left: newLeft,
top: newTop,
centerH: newLeft + boxWidth / 2 - 13 / 2,
centerV: newTop + boxHeight / 2 - 12 / 2,
}
})

setInitPoints((prev) => ({ ...prev, move: { x: clientX, y: clientY } }))
}

原稿问题:handleImageMove 里 clientX / clientY / boxWidth / boxHeight 全是未定义变量,真跑起来第一行就 ReferenceError。触点必须从 e.touches[0] 取,框尺寸要么从 prev、要么从 clipPoints 取。

6. Canvas 导出:dpr 只乘一次

导出时把显示坐标还原成原图坐标,dpr 交给 getCanvasCtx 内部统一处理:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
const onFinish = () => {
const { boxWidth, boxHeight, left, top } = clipPoints
const { scale } = imgInfo

// 裁剪区域在「原图像素」下的宽高,这里不乘 dpr
const clipW = boxWidth / scale
const clipH = boxHeight / scale

getCanvasCtx('canvas', clipW, clipH).then(({ ctx, canvas }) => {
const img = canvas.createImage()
img.src = imgUrlState
img.onload = () => {
ctx.clearRect(0, 0, clipW, clipH)
// 九参写法:源矩形 = 裁剪框覆盖的原图区域,目标矩形 = 逻辑尺寸(dpr 由 ctx.scale 承担)
ctx.drawImage(img, left / scale, top / scale, clipW, clipH, 0, 0, clipW, clipH)
}
canvasRef.current = canvas
})
}

utils/canvas.tsx 里 dpr 只出现一次,就是设置画布尺寸的时候:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
export const getCanvasCtx = async (selectorID = '', width: number, height: number) => {
return new Promise((resolve, reject) => {
createSelectorQuery()
.select(`#${selectorID}`)
.fields({ node: true, size: true })
.exec((res) => {
if (!res[0]) {
reject({ msg: '获取 canvas 失败' })
return
}
const canvas = res[0].node
const ctx = canvas.getContext('2d')
const { pixelRatio } = getWindowInfo()
const dpr = pixelRatio >= 3 ? 1 : pixelRatio // ★ 唯一一次乘 dpr

canvas.width = width * dpr
canvas.height = height * dpr
ctx.scale(dpr, dpr) // 之后所有绘制都用逻辑尺寸,不必再管 dpr
resolve({ ctx, canvas })
})
})
}

原稿问题:clipW = boxWidth / scale * dpr 已经乘了一次 dpr,getCanvasCtx 里又 canvas.width = width * dpr 乘了第二次,画布边长变成期望值的 dpr²,再配上 ctx.scale(dpr, dpr),九参 drawImage 的目标尺寸会被放大到画布之外,导出结果是裁掉一大块的图。统一约定:只有设置 canvas.width / height 时乘一次 dpr,其余全部用逻辑尺寸。

保存到相册:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
const onSave = async (canvas) => {
showLoading({ title: '保存中' })
const { tempFilePath } = await canvasToTempFilePath({
canvas, x: 0, y: 0,
destWidth: canvas.width, // 画布已含 dpr 放大,直接按画布尺寸导出
destHeight: canvas.height,
fileType: 'png',
})
saveImageToPhotosAlbum({
filePath: tempFilePath,
success: () => {
hideLoading()
onCancel()
},
fail: () => {
hideLoading()
showToast({ title: '保存失败,请检查相册权限', icon: 'none' })
},
})
}

原稿里 destWidth 用的是 canvas.width * 0.5,那是「dpr 乘了两次」之后的补偿手段;dpr 收敛到一处以后这半个系数就没必要了。

7. 用 border-style 画 L 形控制点

styles/index.scss:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
.point {
height: 40rpx;
width: 40rpx;
border-width: 10rpx;
border-style: none; /* 默认不显示边框 */
border-color: green;
background-color: transparent;

&-left { border-top-style: double; border-left-style: double; } /* 左上角 L */
&-right { border-left-style: double; border-bottom-style: double; }
&-top { border-top-style: double; border-right-style: double; }
&-bottom { border-bottom-style: double; border-right-style: double; }
&-centerH { border-top-style: double; } /* 上下中点:一条横线 */
&-centerV { border-left-style: double; } /* 左右中点:一条竖线 */
}

『只开两条边的边框就得到一个 L 形角标』——不用图片、不用旋转,8 个控制点共用一套样式。

clipPath 挖洞的写法:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
<Image
src={imgUrlState}
mode="widthFix"
className="absolute z-20 w-screen"
style={{
clipPath: `polygon(
${clipPoints.left}px ${clipPoints.top}px,
${clipPoints.left + clipPoints.boxWidth}px ${clipPoints.top}px,
${clipPoints.left + clipPoints.boxWidth}px ${clipPoints.top + clipPoints.boxHeight}px,
${clipPoints.left}px ${clipPoints.top + clipPoints.boxHeight}px)`,
}}
onTouchStart={(e) => handlePointStart(e, 'move')}
onTouchMove={(e) => handleImageMove(e)}
/>

polygon 的顶点必须按左上 → 右上 → 右下 → 左下顺序连,否则会得到自交图形,挖出来是反的。

踩坑

  • **touchstart 就要 preventDefault()**:低端安卓不加会导致 touchend 永远不触发,按钮状态卡死。
  • 最小尺寸约束要放在「贴边」判断之后:贴边时(_left <= 0)框宽不能再收缩,否则手指继续往左拖会把框压成 0 甚至负数。
  • initPoints 每次 move 后必须刷新:增量位移模型下忘记更新起点,位移会按倍数累积,框直接飞出屏幕。
  • 控件显隐要跟着尺寸走:四边中点只在框足够大时才渲染,否则小框里按钮全叠在一起。
    1
    2
    {clipPoints.boxWidth > 30 && <>{/* centerTop / centerBottom */}</>}
    {clipPoints.boxHeight > 30 && <>{/* centerLeft / centerRight */}</>}
  • 导出前要等一帧:img.onload 里 drawImage 之后立刻 canvasToTempFilePath 可能拿到空白图,用 requestAnimationFrame 兜底比 setTimeout 更准(九宫格页就是这么做的)。
  • query 参数只能是字符串:数组 / 对象必须 JSON.stringify,含 ?、&、% 时必须 encodeURIComponent,接收端对应 decodeURIComponent + JSON.parse。这是小程序路由最常见的类型坑。
  • **临时路径能直接喂 <Image> 和 canvas.createImage()**:tempFilePaths[0] 不需要先上传,这正是本页 imgUrlState 能直接吃 query 的原因。
  • 本页没有缩放:注释里也写明了「没有缩放版本」,放大镜效果是后续待办。要加的话得同时改 scale 基准与所有边界夹取,不能只动图片的 transform。
其他文章
目录导航 置顶
  1. 1. 背景
    1. 1.1. 入口页的参数契约
  2. 2. 实现
    1. 2.1. 1. 分层结构
    2. 2.2. 2. 关键状态
    3. 2.3. 3. 初始化:把原图尺寸换算成显示尺寸
    4. 2.4. 4. 控制点拖拽
    5. 2.5. 5. 整体拖拽
    6. 2.6. 6. Canvas 导出:dpr 只乘一次
    7. 2.7. 7. 用 border-style 画 L 形控制点
  3. 3. 踩坑
请输入关键词进行搜索