淘宝小程序挖坑

一、canvas

调试端显示,真机不显示

解决办法:app.js中,下面的enable属性去掉,这个是为了搞离层canvas设置的,不使用离层canvas不需要

canvas淘宝只支持部分api,类似于字体字重,需要先用再确认能不能用,文档中没写的也不一定不支持。(真他妈坑爹)

 二、会员能力插件使用

商家设置门槛后并不是能随便使用,需要取消门槛,不然会一直回调失败

三、chooseImage api对于安卓和ios的支持不一样,安卓端支持裁剪,表现为方形;ios端不支持裁剪,图片全部上传,需要自己重写裁剪框

const app = getApp();
const { cloud } = getApp();
var windowWRPX = 750
// 拖动时候的 pageX
var pageX = 0
// 拖动时候的 pageY
var pageY = 0
var systemInfo = my.getSystemInfoSync();
var pixelRatio = systemInfo.pixelRatio;
var screenWidth = systemInfo.windowWidth;
var screenHeight = systemInfo.windowHeight - systemInfo.titleBarHeight - systemInfo.statusBarHeight;
var screenRatio = screenWidth / screenHeight;
console.log(screenWidth, screenHeight);

// 调整大小时候的 pageX
var sizeConfPageX = 0
// 调整大小时候的 pageY
var sizeConfPageY = 0

var initDragCutW = 0
var initDragCutL = 0
var initDragCutH = 0
var initDragCutT = 0

// 移动时 手势位移与 实际元素位移的比
var dragScaleP = 2;
Page({
  data: {
    // 进入页面时显示哪个模板
    moduleId: '',
    // 图片数组 1女人2.亚洲男3.外国人
    imgList1: ['https://img.alicdn.com/imgextra/i1/4161332182/O1CN01GDRoVQ1RzOvOWomHg_!!4161332182-2-isvtu.png'],
    imgList2: ['https://img.alicdn.com/imgextra/i3/4161332182/O1CN0168hD831RzOvNEeVKf_!!4161332182-2-isvtu.png'],
    imgList3: ['https://img.alicdn.com/imgextra/i2/4161332182/O1CN01kQIdam1RzOvb6CJxb_!!4161332182-2-isvtu.png'],
    // step控制是否上传过照片
    step: true,
    // 控制是否显示输入框
    showinput: false,
    goal: '',
    action: '',
    // stepcust定制阶段
    stepCust: true,
    // 生成画布图片的比例
    picratio: '',
    picwidth: '',
    picheight: '',
    pixelRatio: 2,
    canvasUrl: '',
    //已经生成海报
    canvasToPic: false,
    // 能否分享
    canIShare: '',
    // 用户id相关
    openId: '',
    userId: '',
    // 弹窗确认
    showPop: false,
    // 等待海报池更新
    canToPool: '',
    showQrcode: true,
    // ios裁剪框
    headImg: '',
    ewmImg: '',
    imageFixed: false, //裁剪浮层
    imageSrc: '', //要裁剪的图片
    imageBase64: "",
    returnImage: '',
    isShowImg: true,
    // 初始化的宽高
    cropperInitW: windowWRPX,
    cropperInitH: windowWRPX,
    // 动态的宽高
    cropperW: windowWRPX,
    cropperH: windowWRPX,
    // 动态的left top值
    cropperL: 0,
    cropperT: 0,
    // 图片缩放值
    scaleP: 0,
    imageW: 0,
    imageH: 0,
    // 裁剪框 宽高
    cutW: 400,
    cutH: 400,
    cutL: 0,
    cutT: 0,
    imgfileid: '',
    // backFromPosterPool:true
  },
  async onLoad(options) {
    console.log(options)
    // 初始化画布
    console.log("第一次进入海报定制页面")
    // 正常流程,
    if (options.data) {
      this.setData({
        moduleId: options.data,
        // backFromPosterPool:false
      })
      app.globalData.swiperIndex = options.data
      console.log(app.globalData.swiperIndex)
    }
    if (app.globalData.openId == '' || app.globalData.userId == '') {
      await this.getCloudInfo()
    }

    this.ctx = my.createCanvasContext('canvas');

    // ios裁剪框
    var _this = this

    my.getImageInfo({
      src: _this.data.imageSrc,
      success: function success(res) {
        console.log("my.getImageInfo-success")
        console.log(res);
        var innerAspectRadio = res.width / res.height;
        console.log("innerAspectRadio", innerAspectRadio);

        var picWidth = 0;
        var picHeight = 0;
        var picTop = 0;
        var picLeft = 0;

        var cutW = 0;
        var cutH = 0;
        var cutT = 0;
        var cutL = 0;


        if (innerAspectRadio > screenRatio) {
          console.log("宽铺满");
          picWidth = screenWidth * 0.9;
          picHeight = Math.ceil(picWidth / innerAspectRadio);
          picLeft = (screenWidth - picWidth) / 2;
          picTop = (screenHeight - picHeight) / 2;


          cutW = Math.ceil(picWidth * 0.5);
          cutH = cutW;
          cutT = (picHeight - cutH) / 2;
          cutL = (picWidth - cutW) / 2;

          console.log(picWidth, picHeight, picLeft, picTop)
          console.log(cutW, cutH, cutT, cutL);

        } else {
          console.log("高铺满");
          picHeight = screenHeight;
          picWidth = Math.ceil(picHeight * innerAspectRadio);
          picLeft = (screenWidth - picWidth) / 2;
          picTop = 0;

          cutW = Math.ceil(picWidth * 0.5);
          cutH = cutW

          cutT = (screenHeight - cutH) / 2;
          cutL = (picWidth - cutW) / 2;

          console.log(picWidth, picHeight, picLeft, picTop)
          console.log(cutW, cutH, cutT, cutL);
        }
        _this.setData({
          cropperW: picWidth,
          cropperH: picHeight,
          // 初始化left right
          cropperL: picLeft,
          cropperT: picTop,
          // 裁剪框  宽高 
          cutW: cutW,
          cutH: cutH,
          cutL: cutL,
          cutT: cutT,
          // 图片缩放值
          scaleP: res.width * pixelRatio / windowWRPX,
          // 图片原始宽度 rpx
          imageW: res.width * pixelRatio,
          imageH: res.height * pixelRatio
        })
        _this.setData({
          isShowImg: true,
        });
        my.hideLoading()

      }
    })
  },
  onShow() {
    console.log('生成页面onshow')

    // if(currentPage.route=='pages/uploadPic/uploadPic'){
    //   // 没参数,跳转到之前选择的模板页面

    // }
  },
  onHide() {
    // this.setData({
    //   canvasToPic: false
    // })
  },
  // 获得用户openid,userid相关信息
  getCloudInfo() {
    app.cloud.function.invoke('v1_c_dream_user', {
    }).then(res => {
      if (res.code == 10000) {
        console.log(res.data[0]);
        app.globalData.openId = res.data[0].openId
        app.globalData.userId = res.data[0]._id
      }
      console.log(app.globalData.openId, app.globalData.userId);
    })
  },
  // 分享设置
  // 分享信息初始化
  onShareAppMessage() {
    if (this.data.imgfileid) {
      return {
        title: '在昂跑,放胆梦',
        desc: '创作放胆海报,集赞赢4000元运动装备',
        imageUrl: 'https://img.alicdn.com/imgextra/i2/4161332182/O1CN019JUyKq1RzOvKs5JsO_!!4161332182-0-isvtu.jpg',
        path: `pages/sharePage/sharePage?openId=${app.globalData.openId}&userId=${app.globalData.userId}&fileId=${this.data.imgfileid}`
      };
    } else {
      return {
        title: '在昂跑,放胆梦',
        desc: '创作放胆海报,集赞赢4000元运动装备',
        imageUrl: 'https://img.alicdn.com/imgextra/i2/4161332182/O1CN019JUyKq1RzOvKs5JsO_!!4161332182-0-isvtu.jpg',
        path: `pages/index/index`
      };
    }

  },
  // input内容获取
  inputGoal(e) {
    this.setData({
      goal: e.detail.value
    })
  },
  inputAction(e) {
    this.setData({
      action: e.detail.value
    })

  },
  // 返回事件
  back() {
    my.navigateTo({
      url: '../chooseModule/chooseModule'
    });
  },
  // 确认下一步
  confirm() {
    this.setData({
      showinput: true
    })
  },
  // 选择图片
  chooseImage() {
    if (app.globalData.userDevice == 'iPhone') {
      this.upEwm()
    } else {
      this.chooseImageAndroid()
    }
    // this.chooseImageAndroid()
  },
  // chooseImageIOS() {

  // },
  // 选择图片=》上传到risk检查=》检测无误 线上环境
  async chooseImageAndroid() {
    let that = this
    let imgList = []
    my.chooseImage({
      count: 1,
      success: (res) => {
        my.showLoading({
          content: '图片审核中...',
          mask: true
        });
        const pic = res
        // console.log('215', res)
        my.getImageInfo({
          src: res.tempFilePaths[0],
          success: (result) => {
            this.setData({
              picratio: result.width / result.height,
              picwidth: result.width,
              picheight: result.height
            })
            console.log(result.width)
            console.log(result.height)
            console.log(this.data.picratio)
          },
        });
        // 临时路径检测安全性
        try {
          cloud.file.uploadFile({
            filePath: pic.apFilePaths[0],
            fileType: 'image',
            fileName: '/user/avatar.png',
          }).then((data) => {
            // 对上传的图片进行安全检测 真机调试有效,测试阶段暂不使用
            my.tb.imgRisk({
              data: {
                cloudFileId: data.fileId
              },
              success(res) {

                console.log('安卓图片审核结果:', res)
                if (res.data.errorCode) {
                  console.log('安卓独特犯病')
                  my.hideLoading()
                  return my.showToast({
                    type: 'fail',
                    content: '上传图片违规,请重新上传'
                  })
                }
                if (res.data.result.suggestion == 'pass') {
                  console.log('图片过审')
                  my.getFileSystemManager().readFile({
                    filePath: pic.tempFilePaths[0],
                    encoding: 'base64',
                    success: res => { //成功的回调  
                      const imgUrl = 'data:image/png;base64,' + res.data
                      const type = '' + that.data.moduleId
                      console.log(imgUrl)
                      switch (type) {
                        case '0':
                          console.log('当前index:', that.data.moduleId)
                          imgList.unshift(imgUrl)
                          that.setData({
                            imgList2: imgList,
                            step: false
                          })
                          my.hideLoading()
                          break;
                        case '1':
                          console.log('当前index:', that.data.moduleId)
                          imgList.unshift(imgUrl)
                          that.setData({
                            imgList1: imgList,
                            step: false
                          })
                          my.hideLoading()
                          break;
                        case '2':
                          console.log('当前index:', that.data.moduleId)
                          imgList.unshift(imgUrl)
                          that.setData({
                            imgList3: imgList,
                            step: false
                          })
                          my.hideLoading()
                          break;
                      }
                    }
                  })
                } else {

                  my.hideLoading()
                  my.showToast({
                    type: 'fail',
                    content: '上传图片违规,请重新上传'
                  })
                  return

                }
              },
              fail(e) {
                console.log(e)
              }
            })
          })

        } catch (e) {
          my.alert({ content: 'error ' + e.message });
        }
      },
    });
  },
  // 测试环境
  // async chooseImage() {

  //   let that = this
  //   console.log('点击选择图片')
  //   let imgList = []
  //   my.chooseImage({
  //     count: 1,
  //     success: (res) => {
  //       console.log('成功进入chooseimage')
  //       my.getImageInfo({
  //         src: res.tempFilePaths[0],
  //         success: (result) => {
  //           this.setData({
  //             picratio: result.width / result.height,
  //             picwidth: result.width,
  //             picheight: result.height
  //           })
  //           console.log(result.width)
  //           console.log(result.height)
  //           console.log(this.data.picratio)
  //         },
  //       });
  //       my.getFileSystemManager().readFile({
  //         filePath: res.tempFilePaths[0],
  //         encoding: 'base64',
  //         success: res => {
  //           const imgUrl = 'data:image/png;base64,' + res.data
  //           console.log('成功进入上传云文件', that.data.moduleId)
  //           const type = '' + that.data.moduleId
  //           console.log(typeof type, type)
  //           switch (type) {
  //             case '0':
  //               console.log('当前index:', that.data.moduleId)
  //               imgList.unshift(imgUrl)
  //               that.setData({
  //                 imgList2: imgList,
  //                 step: false
  //               })

  //               break;
  //             case '1':
  //               console.log('当前index:', that.data.moduleId)
  //               imgList.unshift(imgUrl)
  //               that.setData({
  //                 imgList1: imgList,
  //                 step: false
  //               })
  //               break;
  //             case '2':
  //               console.log('当前index:', that.data.moduleId)
  //               imgList.unshift(imgUrl)
  //               that.setData({
  //                 imgList3: imgList,
  //                 step: false
  //               })
  //               break;

  //           }
  //           // imgList.push(imgUrl)

  //         }
  //       })
  //     }
  //   })
  // },
  // 上传完毕验证 弹窗显示
  openPopWin() {
    this.setData({
      showPop: true
    })
  },
  closePopWin() {
    this.setData({
      showPop: false
    })
  },

  // 开始画canvas
  createCanvas() {
    let that = this
    that.closePopWin()
    that.setData({
      showQrcode: false
    })
    console.log('调用生成canvas')
    // // 正式环境
    // // 先生成数组对象
    let inputArrray = []

    inputArrray.push(this.data.goal)
    inputArrray.push(this.data.action)
    // 文本审核 
    let promise = []
    if (this.data.goal.length == 0 || this.data.action == 0) {
      return my.showToast({
        type: 'fail',
        content: '请输入放胆宣言'
      })
    }
    inputArrray.forEach(item => {
      promise.push(new Promise((resolve, reject) => {
        my.tb.textRiskIdentification({
          data: {
            text: item
          },
          success(res) {
            if (res.data.result.suggestion == 'pass') {
              my.showLoading({
                content: '海报生成中...',
                mask: true
              });
              resolve()
            } else {

              my.showToast({
                type: 'fail',
                content: '输入文字违规,请重新输入',
                success: () => {
                  my.hideLoading();
                }
              })

              return
            }
          }
        })
      }))
    });
    Promise.all(promise).then(() => {
      // 控制显隐
      this.setData({
        stepCust: false,
      })
      const { ctx } = this
      const { pixelRatio, picratio, picheight, picwidth } = this.data
      const type = '' + this.data.moduleId
      switch (type) {
        // 女人
        case '1':
          //  ctx.setTransform(0.5, 0, 0, 0.5, 0, 0) 宽高比
          ctx.drawImage('https://img.alicdn.com/imgextra/i2/4161332182/O1CN01dB7orV1RzOvNEelwT_!!4161332182-2-isvtu.png', 0, 0, 248 * pixelRatio, 396.8 * pixelRatio)
          if (app.globalData.userDevice == 'iPhone') {

            ctx.drawImage(this.data.imgList1[0], 0, 47.6 * pixelRatio, 248 * pixelRatio, 260 * pixelRatio)
          } else {
            ctx.drawImage(this.data.imgList1[0], 0, 0, picwidth, picwidth, 0, 47.6 * pixelRatio, 248 * pixelRatio, 260 * pixelRatio)

          }
          // ios 
          //  二维码
          ctx.drawImage('https://img.alicdn.com/imgextra/i2/4161332182/O1CN01oiQr3B1RzOvX5vg8d_!!4161332182-2-isvtu.png', 192.5 * pixelRatio, 0, 55.8 * pixelRatio, 66.79 * pixelRatio)
          // ctx.drawImage('../../images/chooseModule/cover.png', 0, 64.5 * pixelRatio, 221.25 * pixelRatio, 332.85 * pixelRatio)
          // ctx.drawImage('../../images/chooseModule/module1tag.png', 0, 390 * pixelRatio, 70.95 * pixelRatio, 16.7 * pixelRatio)
          // 文字部分
          ctx.setFontSize(18 * pixelRatio)
          ctx.setFillStyle('white')
          ctx.fillText('为了', 7.5 * pixelRatio, 149.25 * pixelRatio)
          ctx.fillText('而开始', 7.5 * pixelRatio, 202.15 * pixelRatio)
          ctx.fillText('的我 优秀!', 7.5 * pixelRatio, 255.05 * pixelRatio)
          ctx.font = 'normal 900 45px sans-serif'
          // ctx.font='normal 900 45px KaiTi'
          ctx.fillText(this.data.goal, 7.5 * pixelRatio, 175.7 * pixelRatio)
          ctx.fillText(this.data.action, 7.5 * pixelRatio, 228.6 * pixelRatio)
          // 背景图部分
          ctx.draw()
          // 生成链接
          setTimeout(() => {
            ctx.toTempFilePath({
              success(res) {
                // console.log(res)
                try {
                  cloud.file.uploadFile({
                    filePath: res.apFilePath,
                    fileType: 'image',
                    fileName: `/user/${app.globalData.openId}.png`,
                  }).then((data) => {
                    console.log("女人模板的fileid", data.fileId);
                    that.setData({
                      imgfileid: data.fileId
                    })
                    console.log(app.globalData.openId, app.globalData.userId)
                    app.cloud.function.invoke("v1_c_dream_poster_insert", {
                      poster_img: data.fileId,
                      openId: app.globalData.openId,
                      userId: app.globalData.userId
                    }).then(res => {
                      that.setData({
                        canToPool: true
                      })
                      console.log('能去下一步吗:', that.data.canToPool)
                      // 当前无法分享,已经传过海报

                      if (res.code == 20001) {
                        that.setData({
                          canIShare: false
                        })
                      } else if (res.code == 10000) {
                        that.setData({
                          canIShare: true

                        })
                      }

                    })
                  })
                } catch (e) {
                  my.alert({
                    content: 'error ' + e.message
                  });
                }
              }
            })
            ctx.toDataURL({
            }).then((res) => {
              my.hideLoading()
              this.setData({
                canvasUrl: res,
                canvasToPic: true
              })
            });
          }, 1000)
          break;
        case '0':
          // 亚洲男
          //  ctx.setTransform(0.5, 0, 0, 0.5, 0, 0)
          ctx.drawImage('https://img.alicdn.com/imgextra/i2/4161332182/O1CN01Y8MNPF1RzOvSbUeIf_!!4161332182-2-isvtu.png', 0, 0, 248 * pixelRatio, 396.8 * pixelRatio)
          // ctx.drawImage(this.data.imgList2[0], 0, 47.6 * pixelRatio, 248 * pixelRatio, 248 * pixelRatio )
          // ctx.drawImage(this.data.imgList2[0], 0, 0, picwidth, picwidth, 0, 87.975 * pixelRatio, 248 * pixelRatio, 248 * pixelRatio)
          if (app.globalData.userDevice == 'iPhone') {
            ctx.drawImage(this.data.imgList2[0], 0, 87.975 * pixelRatio, 248 * pixelRatio, 248 * pixelRatio)
          } else {
            ctx.drawImage(this.data.imgList2[0], 0, 0, picwidth, picwidth, 0, 87.975 * pixelRatio, 248 * pixelRatio, 248 * pixelRatio)

          }
          // ios ctx.drawImage(this.data.imgList1[0], 0, 0, 248 * pixelRatio, 248 * pixelRatio)
          // ctx.drawImage('../../images/chooseModule/cover.png', 0, 64.5 * pixelRatio, 221.25 * pixelRatio, 332.85 * pixelRatio)
          // ctx.drawImage('../../images/chooseModule/module1tag.png', 0, 390 * pixelRatio, 70.95 * pixelRatio, 16.7 * pixelRatio)
          // 文字部分
          ctx.setFontSize(18 * pixelRatio)
          ctx.setFillStyle('black')
          ctx.fillText('为了', 7.5 * pixelRatio, 149.25 * pixelRatio)
          // ctx.fillText(this.data.goal, 7.5 * pixelRatio, 175.7 * pixelRatio)
          ctx.fillText('而开始', 7.5 * pixelRatio, 202.15 * pixelRatio)
          // ctx.fillText(this.data.action, 7.5 * pixelRatio, 228.6 * pixelRatio)
          ctx.fillText('的我 厉害了!', 7.5 * pixelRatio, 255.05 * pixelRatio)
          ctx.font = 'normal 900 45px sans-serif'
          // ctx.font='normal 900 45px KaiTi'
          ctx.fillText(this.data.goal, 7.5 * pixelRatio, 175.7 * pixelRatio)
          ctx.fillText(this.data.action, 7.5 * pixelRatio, 228.6 * pixelRatio)
          // 背景图部分
          ctx.draw()
          // 生成链接
          setTimeout(() => {
            ctx.toTempFilePath({
              success(res) {
                // console.log('574', res)
                try {
                  cloud.file.uploadFile({
                    filePath: res.apFilePath,
                    fileType: 'image',
                    fileName: `/user/${app.globalData.openId}.png`,
                  }).then((data) => {
                    console.log("亚洲男人模板的fileid", data.fileId);
                    that.setData({
                      imgfileid: data.fileId
                    })
                    app.cloud.function.invoke("v1_c_dream_poster_insert", {
                      poster_img: data.fileId,
                      openId: app.globalData.openId,
                      userId: app.globalData.userId
                    }).then(res => {
                      console.log(res)
                      that.setData({
                        canToPool: true
                      })
                      console.log('能去下一步吗:', that.data.canToPool)
                      // 当前无法分享,已经传过海报
                      if (res.code == 20001) {
                        that.setData({
                          canIShare: false
                        })
                      } else if (res.code == 10000) {
                        that.setData({
                          canIShare: true
                        })
                      }
                    })
                  })
                } catch (e) {
                  my.alert({
                    content: 'error ' + e.message
                  });
                }
              }
            })
            ctx.toDataURL({
            }).then((res) => {
              my.hideLoading()
              this.setData({
                canvasUrl: res,
                canvasToPic: true
              })
            });
          }, 1000)
          break;
        case '2':
          console.log(this.data.imgList3[0])
          //  ctx.setTransform(0.5, 0, 0, 0.5, 0, 0)
          ctx.drawImage('https://img.alicdn.com/imgextra/i2/4161332182/O1CN01dyxx4U1RzOvYwFfHo_!!4161332182-2-isvtu.png', 0, 0, 248 * pixelRatio, 396.8 * pixelRatio)
          // ctx.drawImage(this.data.imgList3[0], 0, 47.6 * pixelRatio, 248 * pixelRatio, 248 * pixelRatio )
          // ctx.drawImage(this.data.imgList3[0], 0, 0, picwidth, picwidth, 0, 68.6 * pixelRatio, 248 * pixelRatio, 248 * pixelRatio)
          if (app.globalData.userDevice == 'iPhone') {
            ctx.drawImage(this.data.imgList3[0], 0, 68.6 * pixelRatio, 248 * pixelRatio, 260 * pixelRatio)
          } else {
            ctx.drawImage(this.data.imgList3[0], 0, 0, picwidth, picwidth, 0, 68.6 * pixelRatio, 248 * pixelRatio, 260 * pixelRatio)

          }
          // ios ctx.drawImage(this.data.imgList1[0], 0, 0, 248 * pixelRatio, 248 * pixelRatio)
          // ctx.drawImage('../../images/chooseModule/cover.png', 0, 64.5 * pixelRatio, 221.25 * pixelRatio, 332.85 * pixelRatio)
          // ctx.drawImage('../../images/chooseModule/module1tag.png', 0, 390 * pixelRatio, 70.95 * pixelRatio, 16.7 * pixelRatio)
          // 文字部分
          ctx.setFontSize(18 * pixelRatio)
          ctx.setFillStyle('white')
          ctx.fillText('为了', 7.5 * pixelRatio, 149.25 * pixelRatio)
          // ctx.fillText(this.data.goal, 7.5 * pixelRatio, 175.7 * pixelRatio)
          ctx.fillText('而开始', 7.5 * pixelRatio, 202.15 * pixelRatio)
          // ctx.fillText(this.data.action, 7.5 * pixelRatio, 228.6 * pixelRatio)
          ctx.fillText('的我 Excellent!', 7.5 * pixelRatio, 255.05 * pixelRatio)
          ctx.font = 'normal 900 45px sans-serif'
          // ctx.font='normal 900 45px KaiTi'
          ctx.fillText(this.data.goal, 7.5 * pixelRatio, 175.7 * pixelRatio)
          ctx.fillText(this.data.action, 7.5 * pixelRatio, 228.6 * pixelRatio)
          // 背景图部分
          ctx.draw()
          // 生成链接
          setTimeout(() => {
            ctx.toTempFilePath({
              success(res) {
                // console.log(res)
                try {
                  cloud.file.uploadFile({
                    filePath: res.apFilePath,
                    fileType: 'image',
                    fileName: `/user/${app.globalData.openId}.png`,
                  }).then((data) => {
                    console.log("欧美男人模板的fileid", data.fileId);
                    that.setData({
                      imgfileid: data.fileId
                    })
                    app.cloud.function.invoke("v1_c_dream_poster_insert", {
                      poster_img: data.fileId,
                      openId: app.globalData.openId,
                      userId: app.globalData.userId
                    }).then(res => {
                      that.setData({
                        canToPool: true
                      })
                      console.log('能去下一步吗:', that.data.canToPool)
                      // 当前无法分享,已经传过海报
                      if (res.code == 20001) {
                        that.setData({
                          canIShare: false
                        })
                      } else if (res.code == 10000) {
                        that.setData({
                          canIShare: true
                        })
                      }

                    })
                  })
                } catch (e) {
                  my.alert({
                    content: 'error ' + e.message
                  });
                }
              }
            })
            ctx.toDataURL({
            }).then((res) => {
              my.hideLoading()
              this.setData({
                canvasUrl: res,
                canvasToPic: true
              })
            });
          }, 1000)
          break;
      }
      //   const { ctx } = this
      //   const { pixelRatio, picratio } = this.data
      //   //  ctx.setTransform(0.5, 0, 0, 0.5, 0, 0)
      //   ctx.drawImage('../../images/chooseModule/module1outline.png', 0, 0, 248 * pixelRatio, 441.5 * pixelRatio)
      //   ctx.drawImage(this.data.imgList[0], 0, 64.5 * pixelRatio, 221.25 * pixelRatio, 221.25 * pixelRatio / picratio)
      //   // ctx.drawImage(this.data.imgList[0],0,64.5,221.25,275.41)
      //   ctx.drawImage('../../images/chooseModule/cover.png', 0, 64.5 * pixelRatio, 221.25 * pixelRatio, 332.85 * pixelRatio)
      //   ctx.drawImage('../../images/chooseModule/module1tag.png', 0, 390 * pixelRatio, 70.95 * pixelRatio, 16.7 * pixelRatio)
      //   // 文字部分
      //   ctx.setFontSize(20 * pixelRatio)
      //   ctx.setFillStyle('white')
      //   ctx.fillText('为了', 7.5 * pixelRatio, 269 * pixelRatio)
      //   ctx.fillText(this.data.goal, 7.5 * pixelRatio, 295 * pixelRatio)
      //   ctx.fillText('而开始', 7.5 * pixelRatio, 323 * pixelRatio)
      //   ctx.fillText(this.data.action, 7.5 * pixelRatio, 351 * pixelRatio)
      //   ctx.fillText('的我 厉害了', 7.5 * pixelRatio, 377 * pixelRatio)
      //   // 背景图部分

      //   ctx.draw()
      // })
      // 测试环境
      // 控制显隐
      this.setData({
        stepCust: false,
      })
    })
  },
  toPosterPool() {
    console.log(this.data.canToPool)
    if (this.data.canToPool) {
      console.log('跳转至海报池')
      my.navigateTo({
        url: '../posterPool/posterPool'
      });
    } else {
      my.showToast({
        content: '正在更新海报池,请稍等'
      });
    }

  },
  toShare() {

    if (this.data.canToPool) {
      if (this.data.canIShare) {
        // 唤出分享页面
        my.showSharePanel({
        })

      } else {
        my.showToast({
          type: '',
          content: '已经上传过海报,无法分享当前海报',
          success: () => {
          },
        });
      }
    } else {
      my.showToast({
        content: '正在更新海报池,请稍等'
      });
    }



  },
  longTap() {
    console.log(this.data.canvasUrl)

  },
  // ios裁剪框相关
  // 拖动时候触发的touchStart事件
  contentStartMove(e) {
    console.log("拖动时候触发的touchStart事件");
    pageX = e.touches[0].pageX
    pageY = e.touches[0].pageY
  },
  // 拖动时候触发的touchMove事件
  contentMoveing(e) {
    console.log("拖动时候触发的touchMove事件");
    var _this = this

    var dragLengthX = (pageX - e.touches[0].pageX) * dragScaleP
    var dragLengthY = (pageY - e.touches[0].pageY) * dragScaleP
    var minX = Math.max(_this.data.cutL - (dragLengthX), 0)
    var minY = Math.max(_this.data.cutT - (dragLengthY), 0)
    var maxX = _this.data.cropperW - _this.data.cutW;
    var maxY = _this.data.cropperH - _this.data.cutH;
    var x = Math.min(maxX, minX);
    x = x < 0 ? 0 : x;
    var y = Math.min(maxY, minY);
    y = y < 0 ? 0 : y;
    this.setData({
      cutL: x,
      cutT: y,
    })
    console.log(`${maxX} ----- ${minX}`)
    console.log(`${maxY} ----- ${minY}`)
    pageX = e.touches[0].pageX
    pageY = e.touches[0].pageY
  },

  // 获取图片
  getImageInfo() {
    var _this = this
    console.log(_this.data.imageSrc)
    my.showLoading({
      title: '图片裁剪中...',
    })
    // 将图片写入画布             
    const ctx = my.createCanvasContext('myCanvas')
    ctx.drawImage(_this.data.imageBase64, 0, 0, _this.data.imageW / pixelRatio, _this.data.imageH / pixelRatio)
    var canvasW = (_this.data.cutW / _this.data.cropperW) * (_this.data.imageW / pixelRatio)
    var canvasH = (_this.data.cutH / _this.data.cropperH) * (_this.data.imageH / pixelRatio)
    var canvasL = (_this.data.cutL / _this.data.cropperW) * (_this.data.imageW / pixelRatio)
    var canvasT = (_this.data.cutT / _this.data.cropperH) * (_this.data.imageH / pixelRatio)
    console.log(`canvasW:${canvasW} --- canvasH: ${canvasH} --- canvasL: ${canvasL} --- canvasT: ${canvasT} -------- _this.data.imageW: ${_this.data.imageW}  ------- _this.data.imageH: ${_this.data.imageH} ---- pixelRatio ${pixelRatio}`)
    ctx.draw(true, function () {
      ctx.toTempFilePath({
        x: canvasL,
        y: canvasT,
        width: canvasW,
        height: canvasH,
        destWidth: canvasW,
        destHeight: canvasH,
        success: function (res) {
          console.log('785', res)
          my.hideLoading()
          // 成功获得地址的地方
          _this.showDemo(res.apFilePath);
          //隐藏截取页 
          _this.setData({
            imageFixed: false,
            headImg: res.apFilePath
          })
        }
      })
    })

  },

  showDemo(tempPath) {
    var _this = this;
    let imgList = []
    // console.log("801showDemo", tempPath)
    my.getFileSystemManager().readFile({
      filePath: tempPath,
      encoding: 'base64',
      success: res => { //成功的回调  
        // console.log('806:', res)

        const imgUrl = 'data:image/png;base64,' + res.data;
        const type = '' + _this.data.moduleId
        console.log('type', type)
        // console.log('imgUrl', imgUrl)
        switch (type) {
          case '0':
            console.log('当前index:', _this.data.moduleId)
            imgList.unshift(imgUrl)
            // console.log(imgList)
            _this.setData({
              imgList2: imgList,
              step: false
            })
            // console.log(this.data.imgList2)
            // my.hideLoading()
            break;
          case '1':
            console.log('当前index:', _this.data.moduleId)
            imgList.unshift(imgUrl)
            // console.log(imgList)
            _this.setData({
              imgList1: imgList,
              step: false
            })
            // my.hideLoading()
            break;
          case '2':
            // console.log('当前index:', _this.data.moduleId)
            imgList.unshift(imgUrl)
            // console.log(imgList)
            _this.setData({
              imgList3: imgList,
              step: false
            })
            // my.hideLoading()
            break;
        }
        _this.setData({
          headImg: imgUrl
        })

      }

    });

  },
  // 设置大小的时候触发的touchStart事件
  dragStart(e) {
    var _this = this
    sizeConfPageX = e.touches[0].pageX
    sizeConfPageY = e.touches[0].pageY
    initDragCutW = _this.data.cutW
    initDragCutL = _this.data.cutL
    initDragCutT = _this.data.cutT
    initDragCutH = _this.data.cutH
  },
  // 设置大小的时候触发的touchMove事件
  dragMove(e) {
    var _this = this
    var touch = e.touches[0];
    var dragLengthX = (sizeConfPageX - touch.pageX) * dragScaleP;
    var dragLengthY = (sizeConfPageY - touch.pageY) * dragScaleP;
    if (initDragCutH >= dragLengthY && initDragCutW >= dragLengthX) {

      var temp = 0;

      // bottom 方向的变化
      if ((dragLengthY < 0 && _this.data.cropperH > initDragCutT + _this.data.cutH) || (dragLengthY > 0)) {
        temp = initDragCutH - dragLengthY;
      }
      // right 方向的变化
      if ((dragLengthX < 0 && _this.data.cropperW > initDragCutL + _this.data.cutW) || (dragLengthX > 0)) {
        temp = initDragCutW - dragLengthX;
      }

      var min = _this.data.cropperW < _this.data.cropperH ? _this.data.cropperW : _this.data.cropperH;

      if (temp > min) {
        temp = min;
      }
      this.setData({
        cutW: temp,
        cutH: temp,
      })

    } else {
      return
    }
  },
  // 上传操作
  upEwm: function () {
    var _this = this;
    console.log("upEwm");
    my.chooseImage({
      count: 1, // 默认9
      sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图,默认二者都有
      sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机,默认二者都有
      success: function (res) {
        console.log('chooseImage-success')
        console.log(res)
        my.showLoading({
          content: '图片上传中...',
          mask: true
        });
        // 返回选定照片的本地文件路径列表,tempFilePath可以作为img标签的src属性显示图片
        var tempFilePaths = res.apFilePaths[0];
        try {
          cloud.file.uploadFile({
            filePath: tempFilePaths,
            fileType: 'image',
            fileName: '/user/avatar.png',
          }).then((data) => {
            console.log('ios data:', data)
            my.tb.imgRisk({
              data: {
                cloudFileId: data.fileId
              },
              success(res) {
                console.log('ios图片审核结果:', res)
                if (res.data.errorCode) {
                  console.log('ios独特犯病')
                  my.hideLoading()
                  return my.showToast({
                    type: 'fail',
                    content: '上传图片违规,请重新上传'
                  })
                }
                if (res.data.result.suggestion == 'pass') {
                  my.hideLoading()
                  console.log('图片过审')

                  // start
                  my.getImageInfo({
                    src: tempFilePaths,
                    success: function success(res) {
                      console.log('getImageInfo', res)
                      var innerAspectRadio = res.width / res.height;
                      console.log('bili' + innerAspectRadio)
                      // 根据图片的宽高显示不同的效果   保证图片可以正常显示

                      my.getFileSystemManager().readFile({
                        filePath: tempFilePaths,
                        encoding: 'base64',
                        success: res => { //成功的回调  
                          const imgUrl = 'data:image/png;base64,' + res.data;

                          _this.setData({
                            imageSrc: tempFilePaths,
                            imageFixed: true,
                            imageBase64: imgUrl
                          })
                        }
                      });

                      var innerAspectRadio = res.width / res.height;
                      console.log("innerAspectRadio", innerAspectRadio);

                      var picWidth = 0;
                      var picHeight = 0;
                      var picTop = 0;
                      var picLeft = 0;

                      var cutW = 0;
                      var cutH = 0;
                      var cutT = 0;
                      var cutL = 0;


                      if (innerAspectRadio > screenRatio) {
                        console.log("宽铺满");
                        picWidth = screenWidth * 0.9;
                        picHeight = Math.ceil(picWidth / innerAspectRadio);
                        picLeft = (screenWidth - picWidth) / 2;
                        picTop = (screenHeight - picHeight) / 2;


                        cutW = Math.ceil(picWidth * 0.5);
                        cutH = cutW;
                        cutT = (picHeight - cutH) / 2;
                        cutL = (picWidth - cutW) / 2;

                        console.log(picWidth, picHeight, picLeft, picTop)
                        console.log(cutW, cutH, cutT, cutL);

                      } else {
                        console.log("高铺满");
                        picHeight = screenHeight;
                        picWidth = Math.ceil(picHeight * innerAspectRadio);
                        picLeft = (screenWidth - picWidth) / 2;
                        picTop = 0;

                        cutW = Math.ceil(picWidth * 0.5);
                        cutH = cutW

                        cutT = (screenHeight - cutH) / 2;
                        cutL = (picWidth - cutW) / 2;

                        console.log(picWidth, picHeight, picLeft, picTop)
                        console.log(cutW, cutH, cutT, cutL);
                      }

                      _this.setData({
                        cropperW: picWidth,
                        cropperH: picHeight,
                        // 初始化left right
                        cropperL: picLeft,
                        cropperT: picTop,
                        // 裁剪框  宽高 
                        cutW: cutW,
                        cutH: cutH,
                        cutL: cutL,
                        cutT: cutT,

                        // 图片缩放值
                        scaleP: res.width * pixelRatio / windowWRPX,
                        // 图片原始宽度 rpx
                        imageW: res.width * pixelRatio,
                        imageH: res.height * pixelRatio
                      })

                      _this.setData({
                        isShowImg: true
                      })

                    }
                  })
                } else {
                  my.hideLoading();
                  my.showToast({
                    type: 'fail',
                    content: '上传图片违规,请重新上传'
                  })
                  return
                }
              }
            })
          })
        } catch (error) {
          console.log({ content: 'error ' + e.message })
        }

      }
    })
  }
});

 四、几点注意

1.首屏动画不要使用gif,使用apng

2.线上环境cdn,图片使用cdn永久可用,其他资源文件不可以,需要即时生成临时路径

3.二楼适配需要提前做好,申请报备时就需要处理

五、附项目中使用的媒体查询

@media screen and (min-aspect-ratio:46/100){
  .body-container{
    height: 75%;
  }
  .rankTitle{
    top: 13.9%;
  }
  .prize{
    top: 20.7%;
  }
  .bottom-container {
    height: 25%;
  }
}
/* xuhua  x*/
@media screen and (min-aspect-ratio: 48/100) {
    .body-container {
        height: 75%;
    }
.prize{
    top: 18.7%;
  }
  .myRank{
    top: 38.75%;;
  }
  .ranklist{
    top: 52%;
  }
    .bottom-container {
        height: 25%;
    }
}
/* iphonex 12  */
@media screen and (min-aspect-ratio: 51/100) {
    .body-container {
        height: 75%;
    }
    
    .ranklist{
    top: 52%;
  }
  .prize{
    top: 20.7%;
  }
.myRank{
    top: 37.75%;;
  }
  .bottom-container {
        height: 25%;
    }
}

@media screen and (min-aspect-ratio: 54/100) {
    .body-container {
        height: 75%;
    }
  .ranklist{
      top: 53%;
    }
    .prize{
      top: 18.7%;
    }
    .myRank{
      top: 38.75%;;
    }
      .bottom-container {
          height: 25%;
      }
}
/* iphone8 */
@media screen and (min-aspect-ratio: 56/100) {
    .body-container {
        height: 85%;
    }
    .prize{
    top: 18.7%;
  }
   .myRank{
      top: 40.75%;;
    }
  .ranklist{
    top: 57%;
  }

    .bottom-container {
        height: 15%;
    }
}
@media screen and (min-aspect-ratio: 60/100) {
    .body-container {
        height: 88%;
    }
    /* .prize{
        top: 12.7%;
      } */
    .top-container {
        height: 9.2rem;
    }
    .bottom-container {
        height: 12%;
    }
}

@media screen and (min-aspect-ratio: 63/100) {
    .top-container {
        height: 9.1rem;
    }
}

  

 

posted @ 2021-08-25 19:34  恣肆zisi  阅读(192)  评论(0)    收藏  举报