小程序canvas上绘制图片真机不显示

小程序在画布上绘制图片时真机不显示

分析:小程序的画布不能绘制网络图片,所以需要wx.downloadFile()或者wx.getImageInfo()方法把网络图片加载到本地再进行绘制

使用wx.downloadFile获取到图片的临时路径

const ctx = wx.createCanvasContext('myCanvas') //获取canvas画布对象
 wx.downloadFile({
          url: 'https://example.com/audio/123',//网络路径
          success: res=> {
          	let path = res.tempFilePath //临时本地路径
          	ctx.drawImage(path, this.shiftSize(0), this.shiftSize(71), this.shiftSize(300), this.shiftSize(168)) //绘制画布上的路径
       		ctx.draw(true) //绘制
          }
        })

使用wx.getImageInfo获取图片临时路径进行绘制

wx.getImageInfo({
      src: app_img, //网络图片路径
      success: res => {
        console.log(res.path,'s2')
        let path = res.path; //图片临时本地路径
        ctx.drawImage(path, this.shiftSize(192), this.shiftSize(249), this.shiftSize(93), this.shiftSize(93))
        ctx.draw(true)
      }
    })

获取临时路径是一个异步操作,所以我们应该给他封装一下promise

getGoodsImgPath:function(){
    return new Promise((success, fail) => {
      if (this.data.goods_img_path) {
        success(this.data.goods_img_path);
      } else {
        wx.getImageInfo({
          src: this.data.goodsInfo.img_url,
          success: res => {
            this.setData({
              goods_img_path: res.path
            })
            success(res.path);
          },
          fail: res => {
            fail(res);
          }
        })
      }
    });
  },

在绘制的函数内调用

this.getGoodsImgPath().then((res) => {
        ctx.save()//保存当前的绘图上下文。
        ctx.drawImage(res, this.shiftSize(0), this.shiftSize(71), this.shiftSize(300), this.shiftSize(168));//绘制图片
        ctx.restore()
        // ctx.draw(true)
        this.getQrCodePath().then((res) => {
          ctx.save()//保存当前的绘图上下文。
          ctx.drawImage(res, this.shiftSize(192), this.shiftSize(249), this.shiftSize(93), this.shiftSize(93))
          // ctx.draw(true)
          ctx.restore()
          ctx.draw()
        });
      });

猜你喜欢

转载自blog.csdn.net/weixin_42215897/article/details/94382577
今日推荐