经验首页 前端设计 程序设计 Java相关 移动开发 数据库/运维 软件/图像 大数据/云计算 其他经验
当前位置:技术经验 » 移动开发 » 微信小程序 » 查看文章
微信小程序之html5 canvas绘图并保存到系统相册
来源:jb51  时间:2019/6/21 10:04:39  对本文有异议

开始实现之前先上个效果图

 

tips

1.网络图片需先配置download域名,可通过wx.getImageInfo转为临时路径;

2.个人习惯问题,我习惯使用async-await语法,所以需要引入regenerator这个库,使用方式可网上查。

一、封装通用微信api返回为Promise对象

/datas/common.js

  1. // 封装获取微信图片信息。
  2. export const getWxImageInfo = (imgPath) => {
  3. return new Promise((resolve, reject) => {
  4. wx.getImageInfo({
  5. src: imgPath,
  6. success: res => {
  7. resolve(res)
  8. },
  9. fail: res => {
  10. reject(res)
  11. }
  12. })
  13. })
  14. }
  15.  
  16. // 封装获取节点选择器信息
  17. export const getSelectQurey = (queryStr) => {
  18. return new Promise(resolve => {
  19. var query = wx.createSelectorQuery();
  20. query.select(queryStr).boundingClientRect();
  21. query.exec(res => {
  22. resolve(res)
  23. })
  24. })
  25. }
  26.  
  27. // 封装把画布导出生成指定大小的图片
  28. export const canvasToTempFilePath = (width, height, canvasId, fileType = 'jpg') => {
  29. return new Promise((resolve, reject) => {
  30. wx.canvasToTempFilePath({
  31. width,
  32. height,
  33. canvasId,
  34. fileType,
  35. success: res => {
  36. resolve(res)
  37. },
  38. fail: res => {
  39. reject(res)
  40. }
  41. })
  42. })
  43. }
  44.  
  45. // 封装保存图片到系统相册
  46. export const saveImageToPhotosAlbum = (filePath) => {
  47. return new Promise((resolve, reject) => {
  48. wx.saveImageToPhotosAlbum({
  49. filePath,
  50. success: res => {
  51. resolve(res)
  52. },
  53. fail: res => {
  54. reject(res)
  55. }
  56. })
  57. })
  58. }

二、视图的实现

.wxml

  1. <view class="icon-download" catchtap="getCanvas">点击生成图片</view>
  2. <!-- 二维码大图 -->
  3. <view class='shade' wx:if="{{isShowCanvas}}">
  4. <view class='qr-code'>
  5. <canvas class='qr-canvas' canvas-id="qrCanvas" id="qrCanvas"></canvas>
  6. <view class='qr-btn'>
  7. <view class='qr-btn-save' catchtap='saveImageToPhotosAlbumFunc'>保存图片,分享到朋友圈</view>
  8. <view class='qr-btn-cancel' catchtap='hideCanvas'>取消</view>
  9. </view>
  10. </view>
  11. </view>
  12. <!-- 二维码大图.end -->

.wxss

  1. /* 查看大图 */
  2. .shade {
  3. width: 100%;
  4. height: 100%;
  5. background-color: rgba(240, 235, 235, 0.5);
  6. position: fixed;
  7. z-index: 100;
  8. top: 0;
  9. left: 0;
  10. }
  11. .qr-code {
  12. width: 600rpx;
  13. height: 1000rpx;
  14. background-color: #fff;
  15. position: absolute;
  16. top: 50%;
  17. left: 50%;
  18. transform: translate(-50%, -50%); /* margin: 30rpx auto; */
  19. }
  20. .qr-canvas {
  21. display: block;
  22. background-color: #fff;
  23. margin: 0 auto;
  24. width: 600rpx;
  25. height: 900rpx;
  26. }
  27. .qr-btn {
  28. width: 600rpx;
  29. height: 100rpx;
  30. line-height: 100rpx;
  31. margin: 0 auto;
  32. font-size: 28rpx;
  33. color: #fff;
  34. display: flex;
  35. background-color: #658dc5;
  36. }
  37. .qr-btn-save {
  38. flex: 0 0 500rpx;
  39. text-align: center;
  40. border-right: 1rpx solid #fff;
  41. }
  42. .qr-btn-cancel {
  43. text-align: center;
  44. flex: 0 0 100rpx;
  45. }

三、创建canvas并保存到系统相册

tips

商品图是正方形的,所以这里商品图的宽高都用canvas的宽文字不能换行,这里只是简单的处理了一下
 

注意: wx.canvasToTempFilePath(Object object, Object this) 这个的使用,文档有一句话需要注意的:“把当前画布指定区域的内容导出生成指定大小的图片。在 draw() 回调里调用该方法才能保证图片导出成功。”

  1. const app = getApp()
  2. const regeneratorRuntime = app.globalData.regeneratorRuntimeconst
  3. const util = require('../../utils/util.js')
  4. import {
  5. getSelectQurey,
  6. getWxImageInfo,
  7. canvasToTempFilePath,
  8. saveImageToPhotosAlbum
  9. } from '../../datas/common.js'
  10.  
  11. Page({
  12. data: {
  13. isShowCanvas: false, // 是否显示canvas
  14. wxaCode: 'https://xxx..jpg', // 商品小程序码
  15. goodsImageUrl: 'https://xxx..jpg', // 商品图片
  16. canvasTempFilePath: '', // canvas导出生成图片的临时路径
  17. },
  18.  
  19. // 点击显示要生成的canvas
  20. getCanvas(e) {
  21. if (!this.data.wxaCode) {
  22. util.showToast('二维码生成失败');
  23. return;
  24. }
  25. this.setData({
  26. isShowCanvas: true
  27. }, () => {
  28. this.createCanvas();
  29. })
  30. },
  31.  
  32. // 隐藏canvas
  33. hideCanvas() {
  34. this.setData({
  35. isShowCanvas: false
  36. })
  37. },
  38.  
  39. // 创建canvas
  40. async createCanvas() {
  41. wx.showLoading({
  42. title: '图片生成中...'
  43. })
  44. const _this = this
  45.  
  46. // 创建节点选择器
  47. const res = await getSelectQurey('#qrCanvas');
  48.  
  49. // canvas的宽高
  50. const cvWidth = res[0].width;
  51. const cvHeight = res[0].height;
  52. const cvSubValue = cvHeight - cvWidth
  53. const qrWidth = cvSubValue / 1.5
  54. const qrMargin = (cvSubValue - qrWidth) / 2
  55. const qrX = cvWidth - qrWidth - qrMargin / 2
  56. const qrY = cvWidth + qrMargin
  57. const shopNameY = cvWidth + cvSubValue - qrWidth
  58.  
  59. // 二维码网络图片转临时路径
  60. let qrImagePath = '';
  61. try {
  62. const wxaCode = _this.data.wxaCode;
  63. const qrImage = await getWxImageInfo(wxaCode);
  64. qrImagePath = qrImage.path
  65. } catch (e) {
  66. wx.hideLoading();
  67. this.hideCanvas();
  68. util.showToast('二维码生成失败');
  69. return;
  70. }
  71.  
  72. // 商品网络图片转临时路径
  73. let goodsImagePath = '/images/default_goods.png';
  74. const goodsImage = _this.data.goodsImageUrl;
  75. if (goodsImage) {
  76. const goodsImageRes = await getWxImageInfo(goodsImage);
  77. goodsImagePath = goodsImageRes.path;
  78. }
  79.  
  80. // 创建canvas
  81. var ctx = wx.createCanvasContext('qrCanvas', _this);
  82.  
  83. // 设置背景
  84. ctx.setFillStyle('#fff');
  85. ctx.fillRect(0, 0, cvWidth, cvHeight);
  86.  
  87. // 设置商品图片 商品图宽高是一样的
  88. ctx.drawImage(goodsImagePath, 0, 0, cvWidth, cvWidth);
  89.  
  90. // 设置二维码图片
  91. ctx.drawImage(qrImagePath, qrX, qrY, qrWidth, qrWidth);
  92.  
  93. // 设置店铺名称
  94. const shopName = '我是店铺名称';
  95. ctx.setFillStyle('black')
  96. ctx.setFontSize(16)
  97. ctx.setTextAlign('left')
  98. ctx.fillText(shopName, 10, shopNameY, cvWidth - qrWidth);
  99.  
  100. // 设置商品名称 文字不能换行,这里只是简单的处理了一下
  101. const goodsName = '一个名字很长很长的商品就问你怕不怕';
  102. let goodsName1 = '';
  103. let goodsName2 = '';
  104. ctx.setFillStyle('black')
  105. ctx.setFontSize(14)
  106. ctx.setTextAlign('left')
  107. if (goodsName.length <= 10) {
  108. ctx.fillText(goodsName, 10, shopNameY + 30, cvWidth - qrWidth);
  109. } else
  110. if (goodsName.length > 10 && goodsName.length <= 22) {
  111. goodsName1 = goodsName.substring(0, 10);
  112. goodsName2 = goodsName.substring(10);
  113. ctx.fillText(goodsName1, 10, shopNameY + 30, cvWidth - qrWidth);
  114. ctx.fillText(goodsName2, 10, shopNameY + 50, cvWidth - qrWidth);
  115. } else {
  116. goodsName1 = goodsName.substring(0, 10);
  117. goodsName2 = goodsName.substring(10, 22) + '...';
  118. ctx.fillText(goodsName1, 10, shopNameY + 30, cvWidth - qrWidth);
  119. ctx.fillText(goodsName2, 10, shopNameY + 50, cvWidth - qrWidth);
  120. }
  121.  
  122. // 设置提示
  123. const tipText = '长按识别小程序,马上下单!';
  124. ctx.setFillStyle('gray')
  125. ctx.setFontSize(8)
  126. ctx.setTextAlign('center')
  127. ctx.fillText(tipText, cvWidth / 2, cvHeight - 10);
  128.  
  129. // 完成
  130. ctx.draw(false, () => {
  131. wx.hideLoading();
  132. _this.canvasToTempFilePathFunc(cvWidth, cvHeight, 'qrCanvas')
  133. });
  134. },
  135.  
  136. // 把当前画布指定区域的内容导出生成指定大小的图片
  137. async canvasToTempFilePathFunc(cvWidth, cvHeight, qrCanvas) {
  138. try {
  139. let res = await canvasToTempFilePath(cvWidth, cvHeight, qrCanvas);
  140. this.setData({
  141. canvasTempFilePath: res.tempFilePath
  142. });
  143. } catch (error) {
  144. console.log(error);
  145. util.showToast(error.errMsg);
  146. }
  147. },
  148.  
  149. // 保存图片到本地
  150. async saveImageToPhotosAlbumFunc() {
  151. try {
  152. let res = await saveImageToPhotosAlbum(this.data.canvasTempFilePath);
  153. console.log(res);
  154. this.hideCanvas();
  155. util.showToast('图片保存成功');
  156. } catch (err) {
  157. console.log(err);
  158. }
  159. }
  160. })

写得比较简单,因为主要是方便自己做记录的,所以也没有考虑到过多的使用场景。

总结

以上所述是小编给大家介绍的微信小程序之html5 canvas绘图并保存到系统相册,希望对大家有所帮助,如果大家有任何疑问欢迎给我留言,小编会及时回复大家的!

 友情链接:直通硅谷  点职佳  北美留学生论坛

本站QQ群:前端 618073944 | Java 606181507 | Python 626812652 | C/C++ 612253063 | 微信 634508462 | 苹果 692586424 | C#/.net 182808419 | PHP 305140648 | 运维 608723728

W3xue 的所有内容仅供测试,对任何法律问题及风险不承担任何责任。通过使用本站内容随之而来的风险与本站无关。
关于我们  |  意见建议  |  捐助我们  |  报错有奖  |  广告合作、友情链接(目前9元/月)请联系QQ:27243702 沸活量
皖ICP备17017327号-2 皖公网安备34020702000426号