index.js 2.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113
  1. // pages/main/index.js
  2. var QR = require("../../utils/qrcode.js");
  3. Page({
  4. data: {
  5. /*
  6. 官网说hidden只是简单的控制显示与隐藏,组件始终会被渲染,
  7. 但是将canvas转化成图片走的居然是fail,hidden为false就是成功的
  8. 所以这里手动控制显示隐藏canvas
  9. */
  10. maskHidden: true,
  11. imagePath: '',
  12. placeholder: 'I love you !'
  13. },
  14. onLoad: function (options) {
  15. // 页面初始化 options为页面跳转所带来的参数
  16. var size = this.setCanvasSize();//动态设置画布大小
  17. var initUrl = this.data.placeholder;
  18. this.createQrCode(initUrl, "mycanvas", size.w, size.h);
  19. },
  20. onReady: function () {
  21. },
  22. onShow: function () {
  23. // 页面显示
  24. },
  25. onHide: function () {
  26. // 页面隐藏
  27. },
  28. onUnload: function () {
  29. // 页面关闭
  30. },
  31. //适配不同屏幕大小的canvas
  32. setCanvasSize: function () {
  33. var size = {};
  34. try {
  35. var res = wx.getSystemInfoSync();
  36. var scale = 750 / 686;//不同屏幕下canvas的适配比例;设计稿是750宽
  37. var width = res.windowWidth / scale;
  38. var height = width;//canvas画布为正方形
  39. size.w = width;
  40. size.h = height;
  41. } catch (e) {
  42. // Do something when catch error
  43. console.log("获取设备信息失败" + e);
  44. }
  45. return size;
  46. },
  47. createQrCode: function (url, canvasId, cavW, cavH) {
  48. //调用插件中的draw方法,绘制二维码图片
  49. QR.qrApi.draw(url, canvasId, cavW, cavH);
  50. var that = this;
  51. //二维码生成之后调用canvasToTempImage();延迟3s,否则获取图片路径为空
  52. var st = setTimeout(function () {
  53. that.canvasToTempImage();
  54. clearTimeout(st);
  55. }, 3000);
  56. },
  57. //获取临时缓存照片路径,存入data中
  58. canvasToTempImage: function () {
  59. var that = this;
  60. wx.canvasToTempFilePath({
  61. canvasId: 'mycanvas',
  62. success: function (res) {
  63. var tempFilePath = res.tempFilePath;
  64. console.log(tempFilePath);
  65. that.setData({
  66. imagePath: tempFilePath,
  67. });
  68. },
  69. fail: function (res) {
  70. console.log(res);
  71. }
  72. });
  73. },
  74. //点击图片进行预览,长按保存分享图片
  75. previewImg: function (e) {
  76. var img = this.data.imagePath
  77. wx.previewImage({
  78. current: img, // 当前显示图片的http链接
  79. urls: [img] // 需要预览的图片http链接列表
  80. })
  81. },
  82. formSubmit: function (e) {
  83. var that = this;
  84. var url = e.detail.value.url;
  85. url = url == '' ? (that.data.placeholder) : (url);
  86. that.setData({
  87. maskHidden: false,
  88. });
  89. wx.showToast({
  90. title: '生成中...',
  91. icon: 'loading',
  92. duration: 1000
  93. });
  94. var st = setTimeout(function () {
  95. wx.hideToast()
  96. var size = that.setCanvasSize();
  97. //绘制二维码
  98. that.createQrCode(url, "mycanvas", size.w, size.h);
  99. that.setData({
  100. maskHidden: true
  101. });
  102. clearTimeout(st);
  103. }, 2000)
  104. }
  105. })