收藏
回答

TypeError: 'xxxx' is not a function怎么解决?

这是我的代码,大神们帮助看看,运行时老是报错,TypeError: _this3.getLessLimitSizeImage is not a function

怎么搞定?

Component({
  data: {
    cw: wx.getSystemInfoSync().windowWidth,
    ITEM_SIZE: 100// 图片大小 单位px
    dragImgList: [], // 图片列表 { src: string, key: number, tranX: number, tranY: number }[]
    imgs: [], // 图片src列表 { src: string, key: number}[]
    containerRes: {}, // 拖拽容器属性
    currentKey: -1// 正在拖拽图片的key
    currentIndex: -1// 正在拖拽图片的index
    tranX: 0// 正在拖拽图片移动的x距离
    tranY: 0// 正在拖拽图片移动的y距离
    uploadPosition: { // upload上传图标位移距离
      tranX: 0,
      tranY: 0,
    }
  },

  onLoad: function (options{
    wx.getPrivacySetting({
      success: res => {
        // console.log(res) // 返回结果为: res = { needAuthorization: true/false, privacyContractName: '《xxx隐私保护指引》' }
        if (res.needAuthorization) {
          // 需要弹出隐私协议
          this.setData({
            showPrivacy: true
          })
        } else {
          // 用户已经同意过隐私协议,所以不需要再弹出隐私协议,也能调用已声明过的隐私接口
          // wx.getUserProfile()
          // wx.chooseMedia()
          // wx.getClipboardData()
          // wx.startRecord()
          wx.getSetting({
            success(res) {
              if (!res.authSetting['scope.writePhotosAlbum']) {
                wx.authorize({
                  scope: 'scope.writePhotosAlbum',
                  success() {
                    // console.log(res.authSetting)
                  }
                })
              }
            }
          })
        }
      }
    });
  },


  lifetimes: {
    ready() {
      this.createSelectorQuery()
        .select(".drag-container")
        .boundingClientRect((res) => {
          this.data.containerRes = res
        }).exec();


      //*************** 图片压缩 ***********
      // 判断图片大小是否满足需求
      function imageSizeIsLessLimitSize(imagePath, limitSize, lessCallBack, moreCallBack{
        wx.getFileSystemManager().getFileInfo({
          filePath: imagePath,
          success(res) {
            console.log("压缩前图片大小:", res.size / 1024"kb");
            if (res.size > 1024 * limitSize) {
              moreCallBack();
            } else {
              lessCallBack();
            }
          },
        });
      }


      /**     * 获取画布图片     */
      // 利用cavas进行压缩 
      function getCanvasImage(
        canvasId,
        currentInstance,
        imagePath,
        imageW,
        imageH,
        getImgsuccess
      {


        console.info(imageW)
        console.info(imageH)
        console.info(canvasId)
        console.info(currentInstance)


        wx.createSelectorQuery()
          .in(currentInstance)
          .select("#" + canvasId)
          .node(({
            node: canvas
          }) => {


            canvas.width = imageW;
            canvas.height = imageH;
            const ctx = canvas.getContext("2d");
            const bg = canvas.createImage();
            bg.src = imagePath;
            bg.onload = () => {
              ctx.save();
              ctx.translate(canvas.width / 2, canvas.height / 2);
              ctx.translate(-canvas.width / 2, -canvas.height / 2);
              ctx.drawImage(bg, 00, imageW, imageH);
              ctx.restore();
              wx.canvasToTempFilePath({
                canvas,
                fileType: "jpg",
                quality: 1,
                success: (res) => {
                  getImgsuccess(res.tempFilePath);
                },
              });
            };
          })
          .exec(function (res{


          });
      }


      // 主调用方法


      /*** 获取小于限制大小的Image     */
      function getLessLimitSizeImage(
        canvasId,
        currentInstance,
        imagePath,
        limitSize = 100,
        drawWidth,
        callBack
      {
        imageSizeIsLessLimitSize(
          imagePath,
          limitSize,
          (lessRes) => {
            callBack(imagePath);
          },
          (moreRes) => {
            wx.getImageInfo({
              src: imagePath,
              success: function (imageInfo{
                var maxSide = Math.max(imageInfo.width, imageInfo.height);
                var windowW = drawWidth;
                var scale = 1;
                if (maxSide > windowW) {
                  scale = windowW / maxSide;
                }
                var imageW = Math.trunc(imageInfo.width * scale);
                var imageH = Math.trunc(imageInfo.height * scale);
                getCanvasImage(
                  canvasId,
                  currentInstance,
                  imagePath,
                  imageW,
                  imageH,
                  (pressImgPath) => {
                    console.log("callback", pressImgPath);
                    getLessLimitSizeImage(
                      canvasId,
                      currentInstance,
                      pressImgPath,
                      limitSize,
                      drawWidth * 0.95,
                      callBack
                    );
                  }
                );
              },
            });
          }
        );
      }


      function getBase64(img{
        return new Promise(function (resolve, reject{
          const FSM = wx.getFileSystemManager();
          FSM.readFile({
            filePath: img,
            encoding: "base64",
            success(data) {
              resolve(data);
            },
          });
        });
      }
    },
  },


  methods: {


    /*** 长按图片*/
    longPress(e) {
      const index = e.mark.index
      const {
        pageX,
        pageY
      } = e.touches[0]
      const {
        top,
        left
      } = this.data.containerRes
      this.setData({
        currentIndex: index,
        tranX: pageX - 50 - left,
        tranY: pageY - 50 - top
      })
    },
    /*** touchMove*/
    touchMove(e) {
      // 如果currentIndex < 0,说明并没有触发longPress
      if (this.data.currentIndex < 0return
      const {
        pageX,
        pageY
      } = e.touches[0]
      const {
        top,
        left
      } = this.data.containerRes
      const tranX = pageX - 50 - left
      const tranY = pageY - 50 - top
      this.setData({
        tranX,
        tranY
      })
      // 对比当前移动的key和停放位置的key,如果不一样就修改位置
      const currentKey = e.mark.key
      const moveKey = this.getMoveKey(tranX, tranY)
      console.log(currentKey, moveKey);
      if (currentKey === moveKey || this.data.currentKey === currentKey) return
      this.data.currentKey = currentKey
      this.insert(currentKey, moveKey)
    },
    /*** 获取移动中的key*/
    getMoveKey(tranX, tranY) {
      const {
        dragImgList: list,
        ITEM_SIZE
      } = this.data
      const _getPositionNumber = (drag) => {
        const positionNumber = Math.round(drag / ITEM_SIZE)
        return positionNumber > 2 ? 2 : positionNumber < 0 ? 0 : positionNumber
      }
      const endKey = 3 * _getPositionNumber(tranY) + _getPositionNumber(tranX)
      return endKey >= list.length ? list.length - 1 : endKey
    },
    /*** 处理移动中key的变化*/
    insert(origin, end) {
      const dragImgList = this.data.dragImgList
      dragImgList.forEach((item) => {
        if (origin < end) {
          if (item.key > origin && item.key <= end) item.key--
          else if (item.key === origin) item.key = end
        } else if (origin > end) {
          if (item.key >= end && item.key < origin) item.key++
          else if (item.key === origin) item.key = end
        }
      })
      this.getListPosition(dragImgList)
    },
    /*** 修改位置*/
    getListPosition(list) {
      const ITEM_SIZE = this.data.ITEM_SIZE
      const dragImgList = list.map((item) => {
        item.tranX = ITEM_SIZE * (item.key % 3);
        item.tranY = Math.floor(item.key / 3) * ITEM_SIZE;
        return item
      })
      this.setData({
        dragImgList,
      })


      const srcList = [dragImgList].sort((a, b) => a.key - b.key).map((item) => item.src)
      this.triggerEvent('updateImage', {
        list: srcList
      })
    },
    /*** touchEnd*/
    touchEnd() {
      this.setData({
        tranX: 0,
        tranY: 0,
        currentIndex: -1,
      })
      this.data.currentKey = -1
    },
    //  修改上传图标位置
    setUploaPosition(listLength) {
      const ITEM_SIZE = this.data.ITEM_SIZE
      const uploadPosition = {
        tranX: listLength % 3 * ITEM_SIZE,
        tranY: Math.floor(listLength / 3) * ITEM_SIZE,
      }
      this.setData({
        uploadPosition,
      })
    },


    /*** 删除图片*/
    deleteImg(e) {
      const key = e.mark.key
      const list = this.data.dragImgList.filter((item) => item.key !== key)
      list.forEach((item) => item.key > key && item.key--)
      this.getListPosition(list)
      this.setUploaPosition(list.length)
    },


    /*** 对多张图片进行预览*/
    previewImg: function (e{
      //获取当前图片的下标
      var index = e.currentTarget.dataset.index;
      //所有图片
      var imgs = this.data.imgs;
      // console.log(imgs);
      wx.previewImage({
        //当前显示图片
        current: imgs[index],
        //所有图片
        urls: imgs
      })
    },


    /*** 上传图片*/
    uploadImage() {
      let {
        dragImgList,
        ITEM_SIZE
      } = this.data
      var that = this;
      var imgs = this.data.imgs;
      if (imgs.length >= 9) {
        that.setData({
          lenMore: 1
        });
        setTimeout(function () {
          that.setData({
            lenMore: 0
          });
        }, 2500);
        return false;
      }


      wx.chooseMedia({
        count: 9 - dragImgList.length,
        sizeType: ['original''compressed'],
        sourceType: ['album''camera'],
        mediaType: 'image',
        success: (res) => {
          // console.log(res.tempFiles)
          const imgList = res.tempFiles.map((item, index) => ({
            tranX: ITEM_SIZE * ((dragImgList.length + index) % 3),
            tranY: Math.floor((dragImgList.length + index) / 3) * ITEM_SIZE,
            src: item.tempFilePath,
            key: dragImgList.length + index
          }))
          var tempFilePaths = res.tempFiles;
          var imgs = that.data.imgs;
          for (var i = 0; i < tempFilePaths.length; i++) {
            let canvasId = 'zipCanvas' //注意这里的id和你在页面中写的html代码的canvas的id要一致
            let imagePath = tempFilePaths[i].tempFilePath; //原图的路径
            // console.log('图片原路径:' + imagePath)
            let limitSize = 512;
            //大小限制2048kb
            let drawWidth = wx.getSystemInfoSync().windowWidth;
            //初始绘画区域是画布自身的宽度也就是屏幕宽度
            wx.showLoading({
              title: '图片压缩中...',
              mask: true
            }) //不需要你可以删掉


            let that = this


            /* canvasId: 微信canvas 2.0 的id值
            currentInstance: 这个很重要, 这就是当前页面组件的实例, 这个就是自定义函数内部用来使用wx.createSelector的api中in(this) 的对象, 不然我们是无法从过query方法去获取当前页面的canvas的。
            imagePath: wx.chooseImage API返回的临时图片经验, 也是通过这个图片我们实现再canvas上绘制截图的。
            limitSize = 100 这个是对小于100KB的图片不进行压缩限制。
            drawWidth: 要压缩到的目标宽度
            callBack: 压缩完成后重新拿到的图片回调函数。 */


            this.getLessLimitSizeImage(canvasId, that, imagePath, 400500);
            console.log(img, "---");
            imgs.push(resPath);
            wx.setStorage({
              key: "imgs_src",
              data: imgs
            })


            dragImgList = dragImgList.concat(imgList)
            this.setUploaPosition(dragImgList.length)
            this.setData({
              dragImgList
            })
          }
        },
        fail(err) {
          // console.log('err', err);
        }
      })
    },
    fail: () => {},
    complete: () => {}
  },
})


回答关注问题邀请回答
收藏

3 个回答

  • 陈政
    陈政
    2023-11-10

    控制台点击报错的文件 里 点击最左边的行 刷新一下可以断点调试

    2023-11-10
    有用 1
    回复
  • optimistic
    optimistic
    2023-11-13

    你这声明的自由函数这么多,this 指向乱的很,直接顶部 const self = this

    调用实例的东西 用 self.xxx 不要用 this了

    2023-11-13
    有用
    回复
  • 啊哈
    啊哈
    2023-11-10

    你代码里面getLessLimitSizeImage函数是单独声明的,都没有绑定到组件的methods里面,用this.getLessLimitSizeImage肯定会报错呀

    2023-11-10
    有用
    回复 2
    • res
      res
      发表于移动端
      2023-11-10
      怎么绑?
      2023-11-10
      回复
    • 啊哈
      啊哈
      2023-11-10回复res
      跟你的previewImg、 uploadImage、deleteImg几个一样的方法就行了。或者直接调用 getLessLimitSizeImage,不用this.getLessLimitSizeImage
      2023-11-10
      回复
登录 后发表内容