index.js 7.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238
  1. import {miniProgramConfig,sharePoster} from '../../api/other';
  2. import {BASE_URL} from '../../utils/request';
  3. import {isLoggedIn,doLogin} from '../../utils/auth';
  4. import { REPORT_BEHAVIOR } from '../../utils/util.js';
  5. const app = getApp();
  6. Page({
  7. data: {
  8. baseUrl:BASE_URL,
  9. banners: [],
  10. introduction:'',
  11. start_time:'',
  12. end_time:'',
  13. ad_img:'',
  14. share_img:'',
  15. pendingAction:null,//按钮类型
  16. loggedIn:false,
  17. showShare: false,
  18. showPoster:false,
  19. posterImg:'',//生成的海报
  20. },
  21. async onLoad(){
  22. const res = await miniProgramConfig();
  23. app.globalData.programConfig = res.data;
  24. this.setData({
  25. banners:res.data.carousels,
  26. introduction:res.data.marathon_event.introduction,
  27. start_time:res.data.marathon_event.start_time,
  28. end_time:res.data.marathon_event.end_time,
  29. ad_img:res.data.ad_img,
  30. share_img:res.data.share_img
  31. })
  32. },
  33. onShow() {
  34. if (typeof this.getTabBar === 'function' && this.getTabBar()) {
  35. this.getTabBar().setData({
  36. selected: 0
  37. })
  38. this.setData({
  39. loggedIn: isLoggedIn()
  40. })
  41. }
  42. },
  43. goPage(e){
  44. const index = e.currentTarget.dataset.index;
  45. if(index == 0){
  46. wx.navigateTo({
  47. url: `/pages/rules/rules?type=${index}`
  48. })
  49. }else if(index == 1){
  50. wx.navigateTo({
  51. url: `/pages/rules/rules?type=${index}`
  52. })
  53. }
  54. },
  55. onShareAppMessage() {
  56. REPORT_BEHAVIOR('分享');
  57. return {
  58. path: '/pages/index/index',
  59. imageUrl: app.globalData.programConfig.share_img
  60. }
  61. },
  62. goRegister(e) {
  63. const action = e.currentTarget.dataset.action;
  64. if (isLoggedIn()) {
  65. this.doAction(action)
  66. }
  67. },
  68. async onGetPhoneNumber(e) {
  69. const action = e.currentTarget.dataset.action;
  70. if (e.detail.errMsg !== 'getPhoneNumber:ok') {
  71. wx.showToast({ title: '授权失败', icon: 'none' })
  72. return
  73. }
  74. const { encryptedData, iv } = e.detail;
  75. try {
  76. wx.login({
  77. success: async loginRes => {
  78. await doLogin({
  79. code: loginRes.code,
  80. phone: { encryptedData, iv }
  81. });
  82. this.setData({ loggedIn: isLoggedIn() })
  83. this.doAction(action);
  84. }
  85. })
  86. } catch (err) {
  87. wx.showToast({ title: '登录失败,请重试', icon: 'none' });
  88. console.error(err);
  89. }
  90. },
  91. doAction(action) {
  92. if (action === 'register') wx.navigateTo({ url: '/pages/register/register' });
  93. if (action === 'invite'){
  94. this.setData({ showShare: true });
  95. };
  96. },
  97. // 弹框取消
  98. onClose(){
  99. this.setData({ showShare: false });
  100. },
  101. // 点击海报生成图片
  102. async openPoster() {
  103. const userInfo = app.globalData.userInfo;
  104. const programConfig = app.globalData.programConfig;
  105. console.log(userInfo)
  106. const posterKey = `posterImg_${userInfo.avatar}_${userInfo.nickname}_${programConfig.share_img}_${programConfig.share_qrcode}`;
  107. const cachedData = wx.getStorageSync('posterCache') || {};
  108. if (cachedData.key === posterKey && cachedData.path) {
  109. this.setData({ posterImg: cachedData.path, showPoster: true });
  110. } else {
  111. this.setData({ showPoster: true }, async () => {
  112. const path = await this.drawPoster();
  113. wx.setStorageSync('posterCache', { key: posterKey, path });
  114. });
  115. }
  116. },
  117. async drawPoster() {
  118. const ctx = wx.createCanvasContext('posterCanvas', this);
  119. const canvasWidth = 300;
  120. const canvasHeight = 600;
  121. const bottomHeight = 80;
  122. const radius = 16; // 圆角半径
  123. ctx.save();
  124. ctx.setFillStyle('#fff');
  125. this.drawRoundRect(ctx, 0, 0, canvasWidth, canvasHeight, radius);
  126. // 背景图
  127. const bgUrl = app.globalData.programConfig.share_img;
  128. if (bgUrl) {
  129. const bgPath = bgUrl.startsWith('http') ? await this.downloadImage(bgUrl) : bgUrl;
  130. ctx.drawImage(bgPath, 0, 0, canvasWidth, canvasHeight - bottomHeight);
  131. }
  132. // 底部白色区域
  133. ctx.setFillStyle('#fff');
  134. ctx.fillRect(0, canvasHeight - bottomHeight, canvasWidth, bottomHeight);
  135. // 用户头像(圆形)
  136. const avatarUrl = app.globalData.userInfo.avatar;
  137. if (avatarUrl) {
  138. const avatarPath = avatarUrl.startsWith('http') ? await this.downloadImage(avatarUrl) : avatarUrl;
  139. const avatarSize = 40;
  140. const avatarX = 20;
  141. const avatarY = canvasHeight - bottomHeight + (bottomHeight - avatarSize) / 2;
  142. ctx.save();
  143. ctx.beginPath();
  144. ctx.arc(avatarX + avatarSize / 2, avatarY + avatarSize / 2, avatarSize / 2, 0, Math.PI * 2);
  145. ctx.clip();
  146. ctx.drawImage(avatarPath, avatarX, avatarY, avatarSize, avatarSize);
  147. ctx.restore();
  148. }
  149. // 昵称
  150. const nickName = app.globalData.userInfo.nickname || '游客';
  151. ctx.setFontSize(16);
  152. ctx.setFillStyle('#000');
  153. const textX = 20 + 40 + 12;
  154. const textY = canvasHeight - bottomHeight + bottomHeight / 2 + 6;
  155. ctx.fillText(nickName, textX, textY);
  156. // 二维码
  157. const qrUrl = app.globalData.programConfig.share_qrcode;
  158. if (qrUrl) {
  159. const qrPath = qrUrl.startsWith('http') ? await this.downloadImage(qrUrl) : qrUrl;
  160. const qrSize = 50;
  161. const qrX = canvasWidth - qrSize - 20;
  162. const qrY = canvasHeight - bottomHeight + (bottomHeight - qrSize) / 2;
  163. ctx.drawImage(qrPath, qrX, qrY, qrSize, qrSize);
  164. }
  165. ctx.restore(); // 恢复裁剪
  166. return new Promise((resolve, reject) => {
  167. ctx.draw(true, () => {
  168. wx.canvasToTempFilePath({
  169. canvasId: 'posterCanvas',
  170. success: res => resolve(res.tempFilePath),
  171. fail: err => {
  172. console.error('生成临时文件失败:', err);
  173. reject(err);
  174. }
  175. }, this);
  176. });
  177. });
  178. },
  179. // 下载网络图片到临时路径
  180. downloadImage(url) {
  181. return new Promise((resolve, reject) => {
  182. wx.downloadFile({
  183. url,
  184. success(res) {
  185. if (res.statusCode === 200) resolve(res.tempFilePath);
  186. else reject(new Error('下载失败'));
  187. },
  188. fail(err) { reject(err); }
  189. });
  190. });
  191. },
  192. // 绘制圆角矩形函数
  193. drawRoundRect(ctx, x, y, w, h, r) {
  194. ctx.beginPath();
  195. ctx.moveTo(x + r, y);
  196. ctx.arcTo(x + w, y, x + w, y + h, r);
  197. ctx.arcTo(x + w, y + h, x, y + h, r);
  198. ctx.arcTo(x, y + h, x, y, r);
  199. ctx.arcTo(x, y, x + w, y, r);
  200. ctx.closePath();
  201. ctx.fill();
  202. ctx.clip(); // 关键:裁剪出圆角
  203. },
  204. closePoster(){
  205. this.setData({ showPoster: false});
  206. },
  207. // 保存相册
  208. savePoster() {
  209. if (!this.data.posterImg) {
  210. wx.showToast({ title: '没有海报图片', icon: 'none' });
  211. return;
  212. }
  213. wx.saveImageToPhotosAlbum({
  214. filePath: this.data.posterImg,
  215. success() { wx.showToast({ title: '保存成功' }); },
  216. fail(err) {
  217. if (err.errMsg.includes('auth')) wx.openSetting();
  218. }
  219. });
  220. },
  221. // 发送朋友
  222. sendImg(){
  223. if (!this.data.posterImg) return;
  224. wx.showShareImageMenu({
  225. path: this.data.posterImg,
  226. success() {},
  227. fail: console.error,
  228. });
  229. }
  230. })