• 小程序 canvas 生成图片


    需在 wxml 中加入 canvas 组件,可设置 hidden 作为容器

    <canvas canvas-id='pickImg' class="upload" hidden></canvas>

    在 js 中控制 canvas 绘制图片

    export function imgUpload(callback){
      wx.chooseImage({
        count: 1, // 默认9
        sizeType: ['compressed'],   // 'original', 'compressed'
        sourceType: ['album', 'camera'],
        success: (res) => {
          // console.log(res)
          res.tempFiles.map(i=>{
            let size = i.size
            if (size > 1 * 1024 * 1024) {
              return wx.showToast({ title: '图片过大', icon: 'none' })
            }else{
              toCanvas(i.path, callback)
            }
          })
        }
      })
    }
    
    function toCanvas(file,callback){
      wx.showLoading({ title: '加载中' })
      let temp = file
      // canvasId 提前定义
      let canvas = wx.createCanvasContext(canvasId)
      // 获取设备系统
      const platform = wx.getSystemInfoSync().platform
      wx.getImageInfo({
        src: temp,
        success: res => {
    
          let imgWidth = res.width> 750 ? 750 : res.width
          let imgHeight = imgWidth * res.height/ res.width
    
          canvas.drawImage(temp, 0, 0, imgWidth, imgHeight)
          canvas.draw(false, () => {
    
            let temp_path = ''
    
            wx.canvasToTempFilePath({
              x: 0,
              y: 0,
               imgWidth,
              height: imgHeight,
              destWidth: imgWidth *2,
              destHeight: imgHeight *2,
              canvasId,
              success: function (res) {
                // console.log(res.tempFilePath)
                temp_path = res.tempFilePath
                // 小程序读取文件管理器 api
                let fileSystemManager = wx.getFileSystemManager()
                fileSystemManager.readFile({
                  filePath: temp_path,
                  encoding: 'base64',
                  success: (data)=>{
                    // console.log(data)
                    let base64 = 'data:image/png;base64,'+data
                    // 自定义接口
                    let { promise } = http.imgUpload( base64 )
                    promise.then(resolve=>{
                      console.log(resolve)
                      callback && callback(filePath, temp_path)
                      wx.hideLoading()
                    })
                  }
                })
              }
            })
            
          })
        },
        fail:(e)=>{
          console.log('getImageInfo error:',e)
          wx.hideLoading()
        }
      })
    }
  • 相关阅读:
    IDL---ENVI
    IDL基础
    IDL_GUI
    .Net MVC+bootstrap Table学习
    .Net中的加密解密
    Linux服务器上安装织梦CMS
    数据仓储之DLL层接口设计
    js获取新浪天气接口
    js动态生成二维码图片
    Jquery点击发送按钮后,按钮文本倒计时
  • 原文地址:https://www.cnblogs.com/_error/p/9578342.html
Copyright © 2020-2023  润新知