2

微信小程序canvas画图drawImage操作 base64 图片

 2 years ago
source link: https://www.geekjc.com/post/61a428d0240760797ce2c52b
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client
关注本站公众号获取最新福利

微信小程序canvas画图drawImage操作 base64 图片

时间: 11/29/2021作者: frontend-联合编辑浏览量: 19

1. 说明:

在微信小程序中canvas drawImage()传入的第一个参数是 imageResource 图片资源路径,这个参数通常由从相册选择图片 wx.chooseImage 或 wx.getImageInfo 获取图片信息来获得。

base64 格式图片数据,无法被 getImageInfo 直接调用

3. 解决思路:

  1. 首先使用 wx.base64ToArrayBuffer 将 base64 数据转换为 ArrayBuffer 数据;(ps: getwxacodeunlimit 返回的分享小程序码就是ArrayBuffer数据)
  2. 使用 FileSystemManager.writeFile 将 ArrayBuffer 写为本地用户路径的二进制图片文件;
  3. 此时的图片文件路径在 wx.env.USER_DATA_PATH 中, wx.getImageInfo 接口能正确获取到这个图片资源,并且 drawImage 也可直接调用该图片资源 ;

ps:图片文件不带base64编码的头信息data:image/png;base64,

 wx.request({
        url: app.globalData.apiUrl + '/app/member_createcode',
        data: {
          scene: "shareuser="+that.data.uid,
          page: "pages/index/index"
        },
        header: {
          'content-type': 'application/x-www-form-urlencoded'
        },
        method: 'POST',
        responseType: 'arraybuffer',
        success: function (res) {
          var url = wx.arrayBufferToBase64(res.data); //服务器回给的getwxacodeunlimit分享小程序码
          that.setData({
            sharecode: url,
            isshow: true
          })

          var fsm =  wx.getFileSystemManager();
          var filePath = wx.env.USER_DATA_PATH + '/share_img.png';
          var buffer = res.data;
          fsm.writeFile({
            filePath: filePath,
            data: buffer,
            encoding:"binary",
            success() {
              that.setData({
                savecode:filePath
              })
            },
          })
        },
        fail: function () { },
})

画图调用:

var ctx = wx.createCanvasContext('myCanvas');
ctx.drawImage(that.data.savecode, 295, 686, 160, 160);
关注下面的标签,发现更多相似的文章

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK