index.js 7.0 KB

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