小程序里做图片裁剪,链路其实很固定:选图拿临时路径 → getImageInfo 读原图尺寸 → 按窗口等比算出显示尺寸 → 分层叠一个可拖拽的裁剪框 → Canvas 2D 按 dpr 绘制并用 clip() 裁剪 → canvasToTempFilePath 导出 → saveImageToPhotosAlbum 存相册。难的不是 API,而是「原图尺寸 / 显示尺寸 / 裁剪尺寸 / 画布尺寸」这四个量的基准统一,以及 dpr 有没有乘对。下面先给原生小程序的完整实现(含圆形裁剪练习页的真实代码),再把踩过的 8 个坑逐条写成「错误写法 → 正确写法」,最后只对照 Taro 三版与原生不同的关键点。
需求与整体流程
用户选一张图,在页面内框选局部,导出并保存到相册。形态上分两类:
- 矩形 / 自由裁剪:框的
x / y / w / h 四个量都可变,四角(或 8 向)拖拽改变尺寸,整体可平移。
- 圆形裁剪:框固定是圆,状态退化成一个
clipWidth(即直径),手指拖动改直径,靠 arc() + clip() 出圆形结果。
不管哪种形态,链路都是七步:
- 取图:
wx.showActionSheet 分发,配 wx.chooseMedia(拍照 / 相册)或 wx.chooseMessageFile(聊天记录),拿到临时路径。
- 量图:
wx.getImageInfo 读原图宽高,wx.getWindowInfo()(旧代码用 getSystemInfoSync())读窗口尺寸。
- 换算:等比缩放到整图可见,得到「显示尺寸」;此后所有拖拽坐标都在显示坐标系里算。
- 分层:底图 → 半透明遮罩 → 裁剪框(内含同位置底图,或直接挖洞)→ 控制点。用叠层而不是真去裁剪 DOM。
- 拖拽 + 边界:每次
touchmove 改 left/top/width/height,同时 clamp 边界、限制最小尺寸。
- 导出:Canvas 2D 按
dpr 设画布 → 绘制(圆形要先 arc + clip)→ wx.canvasToTempFilePath。
- 保存:
wx.saveImageToPhotosAlbum,单独处理拒绝授权。
四个尺寸先分清,后面所有坑都出在这里:
| 量 |
来源 |
用途 |
原图尺寸 naturalW/H |
getImageInfo |
换算基准、高清导出的上限 |
显示尺寸 displayW/H |
等比缩放后 |
触摸 / 拖拽计算的唯一坐标系 |
裁剪尺寸 cropW/H |
用户框选 |
坐标系同显示尺寸 |
画布尺寸 canvas.width/height |
裁剪尺寸 × dpr |
只影响清晰度,不影响布局 |
一、原生实现
1.1 选图:ActionSheet 三分支
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
| selectPhoto () { let itemList = ['拍照', '从手机相册选择', '从聊天记录选择'] wx.showActionSheet({ itemList, success: (action) => { if (action.tapIndex === 0) { wx.chooseMedia({ sourceType: ['camera'] }) } else if (action.tapIndex === 1) { wx.chooseMedia({ sourceType: ['album'] }) } else if ( action.tapIndex === 2) { wx.chooseMessageFile({ count: 99, type: 'all', success: (res) => { this.setData({imagePath: res.tempFiles[0].path}) this.getImageInfo() }}) } } }) },
|
⚠️ 这段代码只有第三条分支接通了:拍照、相册两条分支拿到 chooseMedia 结果后既没有 setData,也没有继续调 getImageInfo(),实际只有「从聊天记录选择」能走完流程。修法见第 2.5 节,三分支要收敛到同一个 afterPick(path)。
1.2 尺寸与 dpr:等比适配
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
| getImageInfo(imagePath: string) { wx.getImageInfo({ src: imagePath, success: (res) => { this.handleImg(res) } }) },
handleImg(res: any) { const sys = wx.getSystemInfoSync() let panelWidth = Math.ceil(sys.windowWidth - 20) let panelHeight = Math.ceil(sys.windowHeight - 100) if (panelHeight / panelWidth >= res.height / res.width) { panelHeight = Math.ceil((panelWidth * res.height) / res.width) } else { panelWidth = Math.ceil((panelHeight * res.width) / res.height) } this.setData({ panelWidth, panelHeight, clipWidth: panelWidth, clipHeight: panelHeight }) },
|
两个要点:
- **取
ceil 且把显示宽高都存进 data**,后续触摸换算全部基于这套值,不要回头用原图尺寸算。
- **显式记一个
scale**:scale = 显示宽 / 原图宽。显示坐标 → 原图坐标是 原图 = 显示 / scale,想按原图清晰度导出时乘这个比值即可。Taro 三版都把这个 scale 抽成了公共变量。
1.3 Canvas 2D 初始化
1
| <canvas id="main" type="2d" style="width: 300px; height: 300px;" />
|
1 2 3 4 5 6 7 8 9
| const query = wx.createSelectorQuery() query.select('#main').fields({ node: true, size: true }).exec((res) => { const canvas = res[0].node const ctx = canvas.getContext('2d') const dpr = wx.getSystemInfoSync().pixelRatio canvas.width = cssWidth * dpr canvas.height = cssHeight * dpr ctx.scale(dpr, dpr) })
|
- 必须是
type="2d" 的新节点,走 fields({ node: true }) 拿;老的 wx.createCanvasContext 那套拿不到 node,canvasToTempFilePath 也就无从传起。
canvas.width/height 只决定清晰度,style 里的宽高决定布局,两者不要混谈。
- 绘制、导出、
createImage() 全程用这同一个 node,不要重复查询。
1.4 裁剪框拖拽
矩形:起点 + 增量模型。 状态里除了框本身,还要存一份 origin* 快照,每次 move 都从快照重算,避免累积误差。
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 55 56 57 58
| data: { panelWidth: 0, panelHeight: 0, clipWidth: 0, clipHeight: 0, clipX: 0, clipY: 0, corner: ['left-top', 'right-top', 'left-bottom', 'right-bottom'], activeIndex: -1, startX: 0, startY: 0, originX: 0, originY: 0, originW: 0, originH: 0, },
touchstart(e: any) { const t = e.touches[0] this.setData({ activeIndex: e.currentTarget.dataset.id, startX: t.clientX, startY: t.clientY, originX: this.data.clipX, originY: this.data.clipY, originW: this.data.clipWidth, originH: this.data.clipHeight }) },
touchmove(e: any) { const t = e.touches[0] const dx = t.clientX - this.data.startX const dy = t.clientY - this.data.startY let { originX, originY, originW, originH } = this.data let clipX = originX, clipY = originY, clipWidth = originW, clipHeight = originH if (this.data.activeIndex === 0) { clipX = originX + dx; clipY = originY + dy clipWidth = originW - dx; clipHeight = originH - dy } else if (this.data.activeIndex === 1) { clipY = originY + dy clipWidth = originW + dx; clipHeight = originH - dy } else if (this.data.activeIndex === 2) { clipX = originX + dx clipWidth = originW - dx; clipHeight = originH + dy } else if (this.data.activeIndex === 3) { clipWidth = originW + dx; clipHeight = originH + dy } if (clipX < 0) { clipWidth += clipX; clipX = 0 } if (clipY < 0) { clipHeight += clipY; clipY = 0 } if (clipX + clipWidth > this.data.panelWidth) clipWidth = this.data.panelWidth - clipX if (clipY + clipHeight > this.data.panelHeight) clipHeight = this.data.panelHeight - clipY const min = 40 if (clipWidth < min || clipHeight < min) return this.setData({ clipX, clipY, clipWidth, clipHeight }) },
touchmoveM(e: any) { const t = e.touches[0] let clipX = this.data.originX + (t.clientX - this.data.startX) let clipY = this.data.originY + (t.clientY - this.data.startY) clipX = Math.min(Math.max(clipX, 0), this.data.panelWidth - this.data.clipWidth) clipY = Math.min(Math.max(clipY, 0), this.data.panelHeight - this.data.clipHeight) this.setData({ clipX, clipY }) },
|
圆形:一个直径走天下。 框宽高相等,拖动时用「手指 X 与图片宽度之差」当直径,小于 100 兜底,避免圆小到看不见。
1 2 3 4 5 6 7 8 9 10 11 12 13 14
| touchmove(event: any) { const [{ pageX }] = event.touches const { imgInitWidth } = this.data let _clipWidth = 0 if (Math.abs(imgInitWidth - pageX) > 100) { _clipWidth = Math.abs(pageX - imgInitWidth) } else { _clipWidth = 100 } this.setData({ clipWidth: _clipWidth }) }, touchend() { this.handleCanvas() },
|
这里的 imgInitWidth 是图片显示宽度,被当成了圆心参考位置,只有图片居中且宽度接近屏幕宽时才准。坐标基准不统一的问题见第 2.8 节。
结构上就是叠三层:
1 2 3 4 5 6 7 8 9 10 11 12
| <view class="container" wx:if="{{imagePath}}"> <view class="crop-content" style="width: 300px; height: 300px;"> <image src="{{imagePath}}" class="img" style="width: {{imgInitWidth}}px; height: {{imgInitHeight}}px;"/> <view class="clip-path" style="width: {{clipWidth}}px; height: {{clipWidth}}px;" bindtouchmove="touchmove" bindtouchend="touchend" /> </view> <canvas id="main" type='2d' style="position: relative;"/> </view>
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
| .container { position: relative; .crop-content { margin-top: 50rpx; position: relative; display: flex; align-items: center; justify-content: center; .img { position: absolute; } .img::after { content: ''; position: absolute; top: 50%; height: 2rpx; width: 100%; background-color: crimson; } .img::before { content: ''; position: absolute; left: 50%; width: 2rpx; height: 100%; background-color: crimson; } .clip-path { border: 3rpx solid rgb(255, 196, 0); border-radius: 50%; z-index: 50; } } }
|
裁剪框就是 .clip-path 这个 border-radius: 50% 的空 view,靠 z-index: 50 压在图上方,只负责显示和收手势;十字准星用两个伪元素画(content: '' 必写,否则不渲染)。
1.5 导出与保存相册
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 55 56
| handleCanvas() { const query = wx.createSelectorQuery() const dpr = wx.getSystemInfoSync().pixelRatio const { imgInitWidth, imgInitHeight,imagePath, clipWidth } = this.data query.select('#main').fields({ node: true, size: true }).exec((res) => { const canvas = res[0].node const preCtx = canvas.getContext('2d') wx.showLoading({title: '正在裁剪...'}) const width = clipWidth const height = clipWidth canvas.width = imgInitWidth * dpr canvas.height = imgInitHeight * dpr const radius = clipWidth / 2 const Cx = width / 2 const Cy = height / 2 const Imgx = width / 2 - radius const Imgy = height / 2 - radius preCtx.scale(dpr, dpr) preCtx.clearRect(0, 0, width, height, clipWidth, clipWidth)
const image = canvas.createImage() image.src = imagePath image.onload = () => { preCtx.beginPath() preCtx.arc(Cx, Cy, radius, 0, 2 * Math.PI, false) preCtx.strokeStyle = '#FFFFFF' preCtx.stroke() preCtx.clip() preCtx.drawImage(image, Imgx, Imgy, clipWidth, clipWidth) preCtx.closePath() preCtx.save() preCtx.restore() } setTimeout(() => { wx.canvasToTempFilePath({ x: Imgx-30, y: 0, width: clipWidth, height: clipWidth, destWidth: clipWidth * dpr, destHeight: clipWidth * dpr, canvas: canvas, success: (res) => { wx.hideLoading() wx.saveImageToPhotosAlbum({ filePath: res.tempFilePath, success: () => { wx.vibrateShort({ type: 'light' }) wx.showModal({ content: '图片已保存到相册~', showCancel: false, confirmText: '好的', confirmColor: '#333' }) }, }) }, fail:() => { wx.hideLoading(); wx.showToast({ title: '保存失败', icon:'error' }) } }) }, 5000) }) }
|
这段是练习页的原样代码,能跑通但不是正确写法:clearRect 多传了两个参数(2.1)、save()/restore() 顺序颠倒(2.2)、画布宽度按 imgInitWidth 设却只画 clipWidth 区域(2.6)、setTimeout(5000) 硬等(2.7)。
可以直接抄的正确骨架是:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
| image.onload = () => { canvas.width = Math.floor(cropW * dpr) canvas.height = Math.floor(cropH * dpr) preCtx.scale(dpr, dpr) preCtx.save() preCtx.beginPath() preCtx.arc(cropW / 2, cropH / 2, cropW / 2, 0, 2 * Math.PI, false) preCtx.clip() preCtx.drawImage(image, -cropX, -cropY, panelWidth, panelHeight) preCtx.restore() wx.canvasToTempFilePath({ canvas, x: 0, y: 0, width: cropW, height: cropH, destWidth: cropW * dpr, destHeight: cropH * dpr, success: (res) => this.saveToAlbum(res.tempFilePath), }) }
|
arc() + stroke() + clip() 是「圆形头像 / 圆形抠图」的标准写法:clip() 之后所有绘制都被限在圆内,drawImage 多出来的部分自动裁掉。
- 矩形裁剪不需要
clip(),直接用 drawImage(img, sx, sy, sw, sh, 0, 0, sw, sh) 九参从源图取矩形区域即可;坐标系是显示尺寸,要先换算到原图:sx = cropX / scale。
- 导出拿到的是临时文件,必须再走
saveImageToPhotosAlbum 才落到相册,fail 里要看是「用户拒绝」还是别的错,必要时引导 wx.openSetting()。
二、常见坑与修正
2.1 clearRect 传了 6 个参数
1 2 3 4 5
| preCtx.clearRect(0, 0, width, height, clipWidth, clipWidth)
preCtx.clearRect(0, 0, width, height)
|
clearRect(x, y, w, h) 的签名只有四个参数,多写的两个会被静默忽略——所以它「看起来能跑」,但读代码的人会误以为这里在做区域裁剪。真正的裁剪靠 clip() 或 drawImage 九参,clearRect 只负责擦干净画布。
2.2 save()/restore() 顺序颠倒
1 2 3 4 5 6 7 8 9 10 11 12
| preCtx.closePath() preCtx.save() preCtx.restore()
preCtx.save() preCtx.beginPath() preCtx.arc(Cx, Cy, radius, 0, 2 * Math.PI, false) preCtx.clip() preCtx.drawImage(image, Imgx, Imgy, clipWidth, clipWidth) preCtx.restore()
|
save() 保存的是当前绘图状态(变换矩阵、裁剪区、样式),restore() 恢复它。两者挨着写等于什么都没做:clip() 建立的圆形裁剪区会一直生效,后面任何一次绘制(比如再画一张图、加水印)都会被这个圆剪掉。正确姿势是「绘制前 save、绘制完 restore」,把 clip 的作用范围圈在中间。
2.3 rgb(108,173,175,0.3) 是非法颜色
1 2 3 4 5
| .mask-bg { background-color: rgb(108, 173, 175, 0.3); }
.mask-bg { background-color: rgba(108, 173, 175, 0.3); }
|
rgb() 是不带透明度的三参语法,0.3 要么被忽略、要么让整条声明无效,遮罩就变成实心或不显示——半透明遮罩失效是最容易被忽略的一类样式 bug。带 alpha 必须用 rgba()(或用 8 位十六进制 #6CADAFFF 风格)。
2.4 clip-path: path() 小程序不支持
1 2 3 4 5 6 7 8 9 10 11 12
| .clip-path { position: absolute; clip-path: path('M15,45 A30,30,0,0,1,75,45 A30,30,0,0,1,135,45 Q135,90,75,130 Q15,90,15,45 Z'); }
.clip-path { border-radius: 50%; overflow: hidden; }
.clip-box { position: absolute; overflow: hidden; } .clip-box .img { position: absolute; }
|
clip-path: path() 是 SVG 路径语法,小程序 WXSS 不支持;即便是 polygon() 也有基础库版本限制。稳的做法是别指望 CSS 裁剪,而是把裁剪框做成一个 overflow: hidden 的容器,里面放一张按反方向平移的底图——视觉上等价于挖洞,且各端表现一致。圆形场景用 border-radius: 50% 就够。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
| wx.chooseMedia({ sourceType: ['camera'] }) wx.chooseMedia({ sourceType: ['album'] })
const afterPick = (path: string) => { this.setData({ imagePath: path }) this.getImageInfo(path) }
wx.chooseMedia({ sourceType: ['camera'], success: (res) => afterPick(res.tempFiles[0].tempFilePath), }) wx.chooseMedia({ sourceType: ['album'], success: (res) => afterPick(res.tempFiles[0].tempFilePath), }) wx.chooseMessageFile({ count: 99, type: 'all', success: (res) => afterPick(res.tempFiles[0].path), })
|
三个入口返回的字段还不一样:chooseMedia 是 res.tempFiles[0].tempFilePath,chooseMessageFile 是 res.tempFiles[0].path。写多分支选择器时务必保证每个分支都跑同一套后续流程,否则就会出现「只有一项能用」的假功能。
2.6 导出时画布宽度未乘 dpr
1 2 3 4 5 6 7 8 9 10 11 12 13 14
| canvas.width = this.data.clipWidth canvas.height = this.data.clipHeight
const dpr = wx.getWindowInfo().pixelRatio canvas.width = Math.floor(clipWidth * dpr) canvas.height = Math.floor(clipHeight * dpr) ctx.scale(dpr, dpr) wx.canvasToTempFilePath({ canvas, width: clipWidth, height: clipHeight, destWidth: clipWidth * dpr, destHeight: clipHeight * dpr, })
|
不乘 dpr,画布内部分辨率就等于 CSS 像素,2 倍 / 3 倍屏上导出的图一定是糊的;destWidth/destHeight 也要跟着乘,否则又会被缩回去。同一类错误还有一个变体:画布按 imgInitWidth * dpr 设,却只 drawImage 了 clipWidth × clipWidth 的区域——画布尺寸和绘制内容的尺寸基准不一致,导出的图就被挤压变形(图片看起来被拉长/压扁,这正是练习页最典型的症状)。记住一句话:画布尺寸永远只对应裁剪区,不要混用显示尺寸。
2.7 setTimeout 硬等图片加载
1 2 3 4 5 6 7 8 9 10
| setTimeout(() => { wx.canvasToTempFilePath({ canvas, }) }, 5000)
image.onload = () => { wx.canvasToTempFilePath({ canvas, }) }
|
硬等既让用户白等 5 秒,又不保证成功(大图 5 秒也未必解码完,小图 1 秒就够)。导出依赖的是「绘制已完成」这个事实,只有 onload(或 requestAnimationFrame 下一帧)能提供这个保证。
2.8 圆心基准与 canvasToTempFilePath 的经验值偏移
1 2 3 4 5 6 7 8 9
| const Cx = width / 2 if (Math.abs(imgInitWidth - pageX) > 100) { } wx.canvasToTempFilePath({ x: Imgx - 30, y: 0, })
const centerX = clipX + clipWidth / 2 const centerY = clipY + clipHeight / 2 wx.canvasToTempFilePath({ x: 0, y: 0, width: clipWidth, height: clipWidth })
|
touchmove 用 imgInitWidth 当圆心、handleCanvas 又用 clipWidth / 2 当圆心,两处各算各的;x: Imgx - 30 这种魔数更是「调到看着对」的产物,换机型、换图片宽高比就崩。裁剪框的位置和尺寸必须是同一个状态对象,导出时直接取这套值,不要手写偏移。
三、Taro 三版实现的差异
Taro 项目的裁剪被拆成 1 个入口 + 3 个实现,思路与原生完全一致,差别集中在「API 换了、状态换成 React、抠图换成 clipPath」这三件事上,这里只记关键点。
| 环节 |
原生 |
Taro |
| 选图 |
chooseMedia / chooseMessageFile |
Taro.chooseImage({ sourceType: ['album','camera'] }) |
| 窗口信息 |
getSystemInfoSync() |
getWindowInfo()(systemInfo 系列已废弃) |
| 抠图 |
半透明遮罩 + 独立裁剪框层 |
<Image> 叠两层 + clipPath: polygon() 内联样式 |
| 拖拽 |
bind:touchstart/touchmove + setData |
onTouchStart/onTouchMove + useState(函数式更新) |
| 位移 |
手写坐标 clamp |
原生 MovableArea / MovableView |
| 导出 |
每处手写 canvas.width |
getCanvasCtx 统一乘 dpr |
| 页面滚动 |
未处理 |
definePageConfig({ disableScroll: true }) |
三个可直接搬走的底座:
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 scale = imgCurWidth / res.width const imgCurHeight = Math.floor(res.height * scale)
export const getCanvasCtx = async (selectorID = '', width: number, height: number) => { return new Promise((resolve, reject) => { createSelectorQuery() .select(`#${selectorID}`).fields({ node: true, size: true }).exec((res) => { const canvas = res[0].node const ctx = canvas.getContext('2d') const dpr = getWindowInfo().pixelRatio >= 3 ? 1 : getWindowInfo().pixelRatio canvas.width = width * dpr canvas.height = height * dpr ctx.scale(dpr, dpr) resolve({ ctx, canvas }) }) }) }
ctx.drawImage(img, sx, sy, sw, sh, 0, 0, cropW, cropH) const { tempFilePath } = await canvasToTempFilePath({ canvas, fileType: 'png' }) saveImageToPhotosAlbum({ filePath: tempFilePath })
|
第 ② 条里 pixelRatio >= 3 ? 1 : pixelRatio 是安卓的坑:3 倍屏上把 dpr 乘进去,画布像素量会撑爆 native buffer,canvasToTempFilePath 直接 fail;宁可在 3 倍屏上退化成 1,也不要黑屏。
三版各自的技术点(也是后续三篇的分工):
| 版本 |
裁剪框 |
图片 |
关键技法 |
| 自由裁剪 |
可缩放,8 向(四角 + 四边中点) |
不动 |
clipPath: polygon() 挖洞;border-style: double 画 L 形控制点 |
| 比例裁剪 |
固定比例,不可缩放 |
不动 |
原生 MovableArea + MovableView;函数式 setState 修高频手势的竞态 |
| 九宫格裁剪 |
固定九宫格 |
可竖直移动 |
MovableView direction="vertical";movable 高度换算;9 张串行导出;dpr 压到 1 |
选择上很简单:只要「框选局部」就用自由裁剪,体验最好;要做头像、封面这类固定比例就用 Movable 方案,代码最少;要发九宫格就上九宫格版,并且一定要把 dpr 压到 1。
后续三篇分别展开:《自由裁剪》逐行拆解 8 向控制点与 clipPath,《Movable 比例裁剪》讲 MovableView 方案与竞态修复原理,《九宫格裁剪》讲 movable 高度换算、9 张串行导出和 dpr 坑。
小结
- 能直接抄的:等比适配公式、
arc + clip + drawImage 圆形裁剪、drawImage 九参矩形裁剪、canvasToTempFilePath → saveImageToPhotosAlbum 导出链、矩形拖拽的「起点 + 增量」状态模型。
- 必须改掉的:
clearRect 多参、save/restore 贴在一起、rgb() 塞 alpha、clip-path: path()、多分支缺 success、导出画布不乘 dpr、setTimeout 硬等、圆心与魔数偏移。
- 一句话:裁剪难的不是 API,而是坐标系与尺寸基准的统一——先把「原图 / 显示 / 裁剪 / 画布」四个量定清楚,再照上面任意一份实现去写,基本不会翻车。