wx2canvas.js 2.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293
  1. import Wxml2Canvas from 'wxml2canvas'
  2. export const startDraw = ()=> {
  3. let that = this
  4. // 创建wxml2canvas对象
  5. let drawMyImage = new Wxml2Canvas({
  6. element: 'myCanvas', // canvas的id,
  7. obj: that, // 传入当前组件的this
  8. width: 200* 2,
  9. height: 200 * 2,
  10. background: '#141415', // 生成图片的背景色
  11. progress(percent) { // 进度
  12. console.log(percent);
  13. },
  14. finish(url) { // 生成的图片
  15. wx.hideLoading()
  16. savePoster(url)
  17. },
  18. error(res) { // 失败原因
  19. console.log(res);
  20. wx.hideLoading()
  21. }
  22. }, this);
  23. let data = {
  24. // 获取wxml数据
  25. list: [{
  26. type: 'wxml',
  27. class: '.my_canvas .my_draw_canvas', // my_canvas要绘制的wxml元素根类名, my_draw_canvas单个元素的类名(所有要绘制的单个元素都要添加该类名)
  28. limit: '.my_canvas', // 要绘制的wxml元素根类名
  29. x: 0,
  30. y: 0
  31. }]
  32. }
  33. // 绘制canvas
  34. drawMyImage.draw(data, this);
  35. }
  36. export const drawMyCanvas = () => {
  37. wx.showLoading()
  38. const that = this
  39. wx.createSelectorQuery()
  40. .select('#my-canvas') // 在 WXML 中填入的 id
  41. .fields({ scrollOffset: true, size: true }, () => {
  42. startDraw()
  43. }).exec(() => {
  44. console.log(888)
  45. })
  46. }
  47. export const savePoster = (url) => {
  48. const that = this
  49. wx.saveImageToPhotosAlbum({
  50. filePath: url,
  51. success: function() {
  52. wx.showToast({
  53. title: '保存成功',
  54. icon: 'none',
  55. duration: 1500
  56. });
  57. },
  58. fail(err) {
  59. if (err.errMsg === "saveImageToPhotosAlbum:fail:auth denied" || err.errMsg === "saveImageToPhotosAlbum:fail auth deny" || err.errMsg === "saveImageToPhotosAlbum:fail authorize no response") {
  60. wx.showModal({
  61. title: '提示',
  62. content: '需要您授权保存相册',
  63. showCancel: false,
  64. success: modalSuccess => {
  65. wx.openSetting({
  66. success(settingdata) {
  67. if (settingdata.authSetting['scope.writePhotosAlbum']) {
  68. wx.saveImageToPhotosAlbum({
  69. filePath: url,
  70. success: function () {
  71. wx.showToast({
  72. title: '保存成功',
  73. icon: 'success',
  74. duration: 2000
  75. })
  76. },
  77. })
  78. } else {
  79. wx.showToast({
  80. title: '授权失败,请稍后重新获取',
  81. icon: 'none',
  82. duration: 1500
  83. });
  84. }
  85. }
  86. })
  87. }
  88. })
  89. }
  90. }
  91. })
  92. }