• 【uniapp】微信小程序canvas签名旋转生成图片


    uniapp开发微信小程序过程中,遇到有审批签名的需求,签名的代码网上还是比较多的,插件市场上大神们比比皆是不再赘述,但遇到一个小细节导致同事有被难倒,无奈咨询于我,细节就是如何把绘制的canvas旋转个角度再生成图片。

    如果只为结论,下面都可以不用看了:旋转图片让后端做,是最快的最方便的(毕竟java有现成工具类),如果真有这种实际业务就交给他们吧不用不好意思,而且后端能做的更多,比如通过色差工具不允许保存空面板等

    但是,套用钱老——“后端能搞的,前端为啥不能搞,前端难道比人家矮一截?”的精神(某些方面实际不止矮一截【狗头】),我们还是要通过研究和实现来增加我们自身的职业自信的,前端已经不是以前的“切图仔”啦。

    那么如何解决呢?且看下面的思路。

    先描述下具体的背景:

            1.审批签名需要用户在一张空白画布上通过手指触碰屏幕并滑动的方式“写字”,完成后保存成一张图片,达到电子签名的目的。

            2.在页面中放置一个canvas标签,设置滑动事件,点击保存时调用uni.canvasToTempFilePath生成临时图片地址,再通过uni.uploadFile上传到后台,就此即可将用户手写的内容生成图片并保存在服务器了。

    但是!一般的签名是需要用户横屏手写的,但对手机来说实际是竖着写的,保存的图片也是按手机(竖长型)的样子来的,在pc端展示的话需要用css旋转才行,但若有后台生成pdf此类需求的话,那就不好去旋转图片了,为了一劳永逸还得从生成的源头控制才行。

    解决思路1:在保存的事件中去旋转canvas

    canvas的上下文是提供旋转函数的canvasContext.rotate,但在实际过程中旋转没效果,而且假若成功,对用户体验也不好,放弃。

    解决思路2:再添加一个“隐藏”的canvas,当画好后,在保存事件中动态将签名canvas的内容旋转复制到“隐藏”的canvas中,再将后者的内容生成图片上传,便能曲线实现我们的需求。

    这个思路也是官方提供的,详见 canvas绘制好怎么旋转? | 微信开放社区

    用代码说话

    1. <script>
    2. import { BASE_URL } from '@/common/config.js'
    3. import { getUToken } from '@/store'
    4. import { storage } from '@/api/api'
    5. import { replaceCurrentSignApi } from '@/api/flow.js'
    6. export default {
    7. name: 'Signature',
    8. data() {
    9. return {
    10. canvasName: 'handWriting',
    11. ctx: '',
    12. startX: null,
    13. startY: null,
    14. canvasWidth: 0,
    15. canvasHeight: 0,
    16. selectColor: 'black',
    17. lineColor: '#1A1A1A', // 颜色
    18. canvas: null,
    19. cavWidth: 2000,
    20. cavWidth1: 2000,
    21. lineSize: 5 // 笔记倍数
    22. }
    23. },
    24. onLoad() {
    25. this.ctx = uni.createCanvasContext('handWriting', this)
    26. this.$nextTick(() => {
    27. uni
    28. .createSelectorQuery()
    29. .select('.handCenter')
    30. .boundingClientRect((rect) => {
    31. this.canvasWidth = rect.width
    32. this.canvasHeight = rect.height
    33. /* 将canvas背景设置为 白底,不设置 导出的canvas的背景为透明 */
    34. this.setCanvasBg('#fff')
    35. })
    36. .exec()
    37. })
    38. },
    39. methods: {
    40. // 笔迹开始
    41. uploadScaleStart(e) {
    42. this.startX = e.changedTouches[0].x
    43. this.startY = e.changedTouches[0].y
    44. //设置画笔参数
    45. //画笔颜色
    46. this.ctx.setStrokeStyle(this.lineColor)
    47. //设置线条粗细
    48. this.ctx.setLineWidth(this.lineSize)
    49. //设置线条的结束端点样式
    50. this.ctx.setLineCap('round') //'butt'、'round'、'square'
    51. //开始画笔
    52. this.ctx.beginPath()
    53. },
    54. // 笔迹移动
    55. uploadScaleMove(e) {
    56. //取点
    57. let temX = e.changedTouches[0].x
    58. let temY = e.changedTouches[0].y
    59. //画线条
    60. this.ctx.moveTo(this.startX, this.startY)
    61. this.ctx.lineTo(temX, temY)
    62. this.ctx.stroke()
    63. this.startX = temX
    64. this.startY = temY
    65. this.ctx.draw(true)
    66. },
    67. /**
    68. * 重写
    69. */
    70. retDraw() {
    71. this.ctx.clearRect(0, 0, 700, 730)
    72. this.ctx.draw()
    73. //设置canvas背景
    74. this.setCanvasBg('#fff')
    75. },
    76. /**
    77. * @param {Object} str
    78. * @param {Object} color
    79. * 选择颜色
    80. */
    81. selectColorEvent(str, color) {
    82. this.selectColor = str
    83. this.lineColor = color
    84. },
    85. // 确认
    86. subCanvas() {
    87. // uni.canvasToTempFilePath({
    88. // canvasId: 'handWriting',
    89. // fileType: 'png',
    90. // quality: 1, //图片质量
    91. // success(res) {
    92. // // console.log(res.tempFilePath, 'canvas生成图片地址');
    93. // const { uToken } = getUToken()
    94. // uni.uploadFile({
    95. // url: `${BASE_URL}${storage}/upload`,
    96. // header: {
    97. // 'staff-token': uToken
    98. // },
    99. // filePath: res.tempFilePath,
    100. // name: 'file',
    101. // formData: {
    102. // plateform: '',
    103. // fileType: 'image'
    104. // },
    105. // success: ({ statusCode, data, errMsg }) => {
    106. // const parseData = JSON.parse(data)
    107. // if (statusCode == 200 && parseData.code == 100) {
    108. // replaceCurrentSignApi({
    109. // fileId: parseData.data.fileId
    110. // }).then(([err, res]) => {
    111. // if (err) {
    112. // uni.showToast('保存签名失败')
    113. // return
    114. // }
    115. // // 返回上一层并传参
    116. // let pages = getCurrentPages() // 获取当前页面栈的实例,以数组形式按栈的顺序给出,第一个元素为首页,最后一个元素为当前页面。
    117. // let prevPage = pages[pages.length - 2] //上一页页面实例
    118. // prevPage.$vm.otherFun(parseData) // 给上一页绑定方法otherFun,传参地址id
    119. // uni.navigateBack()
    120. // })
    121. // } else {
    122. // uni.showToast(errMsg)
    123. // }
    124. // }
    125. // })
    126. // }
    127. // })
    128. const _this = this
    129. uni.canvasToTempFilePath({
    130. canvasId: 'handWriting',
    131. fileType: 'png',
    132. quality: 1, //图片质量
    133. success(res) {
    134. console.log(res.tempFilePath, 'canvas生成图片地址')
    135. wx.getImageInfo({
    136. // 获取图片的信息
    137. src: res.tempFilePath,
    138. success: (res1) => {
    139. console.log(res1)
    140. // 将canvas1的内容复制到canvas2中
    141. let canvasContext = wx.createCanvasContext('handWriting2')
    142. let rate = res1.height / res1.width
    143. let width = 300 / rate
    144. let height = 300
    145. _this.cavWidth = 300 / rate
    146. _this.cavWidth1 = 300
    147. canvasContext.translate(height / 2, width / 2)
    148. canvasContext.rotate((270 * Math.PI) / 180)
    149. canvasContext.drawImage(res.tempFilePath, -width / 2, -height / 2, width, height)
    150. canvasContext.draw(false, () => {
    151. // 将之前在绘图上下文中的描述(路径、变形、样式)画到 canvas 中
    152. wx.canvasToTempFilePath({
    153. // 把当前画布指定区域的内容导出生成指定大小的图片。在 draw() 回调里调用该方法才能保证图片导出成功。
    154. canvasId: 'handWriting2',
    155. fileType: 'png',
    156. quality: 1, //图片质量
    157. success(res2) {
    158. // 调用uni.uploadFile上传图片即可
    159. console.log(res2)
    160. }
    161. })
    162. })
    163. }
    164. })
    165. }
    166. })
    167. // wx.createSelectorQuery()
    168. // .select('#handWriting')
    169. // .fields({ node: true, size: true })
    170. // .exec((res) => {
    171. // console.log(res);
    172. // _this.canvas = res[0].node
    173. // // const rotateCtx = rotateCanvas.getContext('2d')
    174. // })
    175. },
    176. //旋转图片,生成新canvas实例
    177. rotate(cb) {
    178. const that = this
    179. wx.createSelectorQuery()
    180. .select('#handWriting2')
    181. .fields({ node: true, size: true })
    182. .exec((res) => {
    183. const rotateCanvas = res[0].node
    184. const rotateCtx = rotateCanvas.getContext('2d')
    185. //this.ctxW-->所绘制canvas的width
    186. //this.ctxH -->所绘制canvas的height
    187. rotateCanvas.width = this.ctxH
    188. rotateCanvas.height = this.ctxW
    189. wx.canvasToTempFilePath({
    190. canvas: that.canvas,
    191. success(res) {
    192. const img = rotateCanvas.createImage()
    193. img.src = res.tempFilePath
    194. img.onload = function () {
    195. rotateCtx.translate(rotateCanvas.width / 2, rotateCanvas.height / 2)
    196. rotateCtx.rotate((270 * Math.PI) / 180)
    197. rotateCtx.drawImage(img, -rotateCanvas.height / 2, -rotateCanvas.width / 2)
    198. rotateCtx.scale(that.pixelRatio, that.pixelRatio)
    199. cb(rotateCanvas)
    200. }
    201. },
    202. fail(err) {
    203. console.log(err)
    204. }
    205. })
    206. })
    207. },
    208. //取消
    209. saveCanvasAsImg() {
    210. this.retDraw()
    211. uni.navigateBack()
    212. },
    213. //设置canvas背景色 不设置 导出的canvas的背景为透明
    214. //@params:字符串 color
    215. setCanvasBg(color) {
    216. /* 将canvas背景设置为 白底,不设置 导出的canvas的背景为透明 */
    217. //rect() 参数说明 矩形路径左上角的横坐标,左上角的纵坐标, 矩形路径的宽度, 矩形路径的高度
    218. //这里是 canvasHeight - 4 是因为下边盖住边框了,所以手动减了写
    219. this.ctx.rect(0, 0, this.canvasWidth, this.canvasHeight - 4)
    220. // ctx.setFillStyle('red')
    221. this.ctx.setFillStyle(color)
    222. this.ctx.fill() //设置填充
    223. this.ctx.draw() //开画
    224. },
    225. toJSON() {}
    226. }
    227. }
    228. <style>
    229. page {
    230. background: #fbfbfb;
    231. height: auto;
    232. overflow: hidden;
    233. }
    234. .wrapper {
    235. position: relative;
    236. width: 100%;
    237. height: 85vh;
    238. margin: 20rpx 0;
    239. overflow: auto;
    240. display: flex;
    241. align-content: center;
    242. flex-direction: row;
    243. justify-content: center;
    244. font-size: 28rpx;
    245. }
    246. .handWriting {
    247. background: #fff;
    248. width: 100%;
    249. height: 85vh;
    250. }
    251. .handCenter {
    252. border-left: 2rpx solid #e9e9e9;
    253. flex: 5;
    254. overflow: hidden;
    255. box-sizing: border-box;
    256. }
    257. .handBtn button {
    258. font-size: 28rpx;
    259. }
    260. .handBtn {
    261. height: 85vh;
    262. display: inline-flex;
    263. flex-direction: column;
    264. justify-content: space-between;
    265. align-content: space-between;
    266. flex: 1;
    267. }
    268. .delBtn {
    269. width: 200rpx;
    270. position: absolute;
    271. bottom: 350rpx;
    272. left: -35rpx;
    273. transform: rotate(90deg);
    274. color: #666;
    275. }
    276. .subBtn {
    277. width: 200rpx;
    278. position: absolute;
    279. bottom: 52rpx;
    280. left: -35rpx;
    281. display: inline-flex;
    282. transform: rotate(90deg);
    283. background: #29cea0;
    284. color: #fff;
    285. margin-bottom: 60rpx;
    286. text-align: center;
    287. justify-content: center;
    288. }
    289. /*Peach - 新增 - 保存*/
    290. .saveBtn {
    291. width: 200rpx;
    292. position: absolute;
    293. bottom: 590rpx;
    294. left: -35rpx;
    295. transform: rotate(90deg);
    296. color: #666;
    297. }
    298. style>

    代码重点:

     

     看看具体效果吧:

    随便画一个,只有点击保存,再去同步第二个canvas,此时是没点确定的状态。

     

     点击确认,可以看到内容就生成好啦。

     这样,就能前端实现canvas的旋转上传啦。

    后续:

    实际测试过程中,会有画布大小的兼容性问题,具体表现为,在代码里设置的画布背景是白色,在某些屏宽(宽高比比iphone7还大)的iphone上,生成的图片可能会存在右侧一竖列区域(如果没做旋转处理实际上是图片的底部区域)是透明的情况,用图片指示一下。

     可能是由于ctx.clearRect,ctx.rect填充区域同事给写死,或是填充高度和画布高度不一致?,或canvas自己问题,建议在这里就不要动态的获取canvas宽高去动态填充指定范围的颜色了,暴力一点,直接填充2000大小区域,类似于this.ctx.clearRect(0, 0, 2000, 2000),this.ctx.rect(0, 0, 2000, 2000),省时省力哈哈。

    参考资料(资料2仅提供思路,没实现出来):

    canvas绘制好怎么旋转? | 微信开放社区

    微信小程序 图片旋转后上传_big_badwolf的博客-CSDN博客_微信小程序旋转图片后上传

  • 相关阅读:
    2、计算机图形学——视图变换
    Nacos配置管理
    3.11笔记3
    Spring Bean的生命周期
    如何对齐MathType公式和Word文字排版
    new IntersectionObserver 使用笔记
    李超线段树
    隆云通二氧化硫传感器
    LeetCode 2316. 统计无向图中无法互相到达点对数【图,BFS,DFS,并查集】1604
    splunk
  • 原文地址:https://blog.csdn.net/rrrrroy_Ha/article/details/126864111