美文网首页微信小程序开发
微信小程序:一个简单的canvas裁剪图片功能

微信小程序:一个简单的canvas裁剪图片功能

作者: 空箜崆 | 来源:发表于2019-07-12 10:44 被阅读8次

    小程序miniso的一个发布内容截图功能,话不多,先上代码

    wxml文件:
    <view class="cut-1-1 t-c {{cutSelect == 1? 'cut-select':''}}" data-cut="1" bindtap="selectCutType">1:1</view>
    <view class="cut-3-4 t-c {{cutSelect == 2? 'cut-select':''}}" data-cut="2" bindtap="selectCutType">3:4</view>
    
    <block wx:for="{{imgList}}" wx:key="{{index}}" >
          <swiper-item>
            <scroll-view  scroll-top="{{topNum}}" scroll-y class="imgFile {{cutSelect == 1?'view-1-1':'view-3-4'}}" bindscroll="endTou">
              <image src='{{item}}' mode="widthFix"></image>
            </scroll-view >
          </swiper-item>
    </block>
    
    <canvas wx:for="{{imgList}}" wx:for-index="i" canvas-id="myCanvas_{{i}}" style="width: {{width[i]?width[i]*2:750}}rpx; height: {{height[i]?height[i]*2:750}}rpx;"></canvas>
    

    这里是对多张图片进行统一处理,用户选了哪种截图比例,所有图片用统一规格裁剪。
    因为简单,不提供缩放和左右移动,所以只能裁剪竖长图,不支持横长图裁剪。
    topNum用于scroll-view的reset处理

    wxss文件
    .view-1-1 {
      width: 750rpx;
      height: 750rpx;
      overflow: hidden;
    }
    
    .view-3-4 {
      width: 750rpx;
      height: 750rpx;
      padding: 0 94rpx;
      box-sizing: border-box;
      overflow: hidden;
    }
    
    canvas {
      position: absolute;
      /* display: none; */
      left: -999rpx;
      z-index: 0;
    }
    

    裁剪比例的样式,1:1裁剪使用750rpx,3:4使用padding进行视觉上的拉长
    接下来就是重要的代码部分了

    js文件
    cutPic() {
        const _this = this
        if (this.data.cutting) {
          return
        }
        let promiseList = [], ctx = []
        _this.data.imgList.forEach((v, i) => {
          promiseList.push(_this.draw(ctx, v, i))
        })
        wx.showLoading({
          title: '截取中...',
          icon: 'none'
        })
        this.setData({
          cutting: true
        })
        Promise.all(promiseList).then((arr) => {
          wx.setStorageSync("interimImagesList", _this.data.imgFileList)
          _this.uploadPic()
        }, err => {
        })
      },
    

    使用微信自带api,wx.chooseImage将图片保存在imgList数组里,因为裁剪图片用canvas处理会有一定的延迟,所以使用promise进行异步处理

    //获取竖向滑动坐标
      endTou(e) {
        const _this = this
        let y = 'y[' + (_this.data.currentIndex - 1) + '].top'
        _this.setData({
          [y]: e.detail.scrollTop
        })
      },
    

    定义的y数组用于记录每张图片截取的位置。

    //绘制
      draw(ctx, v, i) {
        const _this = this
        let width, height
        return new Promise((resolve, reject) => {
          ctx[i] = wx.createCanvasContext(`myCanvas_${i}`)
          wx.getImageInfo({
            src: v,
            success: function (res) {
              width = 'width[' + i + ']'
              height = 'height[' + i + ']'
              var str = res.height / res.width;//图片的宽高比
              _this.setData({
                [width]: 375,
                [height]: 375 * str
              }, () => {
                ctx[i].drawImage(v, 0, 0, _this.data.width[i], _this.data.height[i])
                ctx[i].draw(false, () => {
                  setTimeout(() => {
                    wx.canvasToTempFilePath({//调用方法,开始截取
                      x: 0,
                      y: _this.data.y[i] ? _this.data.cutSelect == 1 ? _this.data.y[i].top : _this.data.y[i].top / 0.75 : 0,
                      width: 375,
                      height: _this.data.cutSelect == 1 ? 375 : 500,
                      destWidth: 375,
                      destHeight: _this.data.cutSelect == 1 ? 375 : 500,
                      canvasId: 'myCanvas_' + i,
                      success: function (res) {
                        resolve(res.tempFilePath)
                        console.info('canvas', res.tempFilePath)
                        let img = 'imgFileList[' + i + ']'
                        _this.setData({
                          [img]: res.tempFilePath
                        })
                      },
                      fail: function (err) {
                        reject(err)
                        console.info(err)
                      }
                    })
                  }, 1000) // 渲染时间
                })
              })
            }
          })
        })
      },
    

    渲染图片最重要的一步是获得宽高比,所以在canvas绘制之前使用getImageInfo获取到图片信息,var str=res.height/res.width获得高宽比例。
    canvas绘制图片是需要时间,所以setTime了个1秒,不然截出来的图是失败的。这里也可以使用递归的方式来绘制canvas,代码就不给出了,可以自己搜一下。

    总结:

    一个简单的canvas截图就制作完成了。值得注意的是canvas渲染是需要时间的。
    这也算是一个简单的练手吧,下次有什么复杂的截图功能再分享出来吧。

    相关文章

      网友评论

        本文标题:微信小程序:一个简单的canvas裁剪图片功能

        本文链接:https://www.haomeiwen.com/subject/vxzskctx.html