微信小程序 实现canvas按照原图等比例不失真绘制海报图并保存海报图片到本地相册

 1.获取手机宽度 进而设置canvas画布的宽度

onLoad() {
    let that = this;
    // 获取系统信息,设置canvas宽高
    wx.getSystemInfo({
      success(res) {
        that.setData({
          canvasWidth: res.windowWidth
        })
      }
    }) 
  },

2.获取图片信息 将图片保存到本地路径然后再去绘制, 不然容易出现canvas画不上然后保存图片到本地时候出现空白的问题

  make:function(url){
    var that=this;
    console.log(url);
     //获取图片信息
     wx.getImageInfo({
       src: url,
       success: function(res){
         console.log(JSON.stringify(res));
         that.setData({
           imgInfo:res
         });
         console.log(JSON.stringify(that.data.imgInfo));
         let imageSize = util.imageZoomHeightUtil(that.data.imgInfo.width, that.data.imgInfo.height);//根据屏幕宽度
          that.setData({ canvasHeight: imageSize.imageHeight });
         console.log('imageSize等比例' + JSON.stringify(imageSize));
         that.makeCanvas(url);
       }
     })
  },

3.开始绘制图 ctx.draw(false, this.drawCallBack)一定要执行后面的回调函数

makeCanvas: function (url) {
    var ctx = wx.createCanvasContext('canvas')
    ctx.drawImage(url, 0, 0, this.data.imgInfo.width, this.data.imgInfo.height, 0, 0, this.data.canvasWidth, this.data.canvasHeight);
    ctx.draw(false, this.drawCallBack)
  },
  drawCallBack: function () {
    var that = this
    wx.canvasToTempFilePath({
      x: 0,
      y: 0,
      width: that.data.canvasWidth,
      height: that.data.canvasHeight,
      canvasId: 'canvas',
      fileType: 'jpg',
      success: function (res) {
        // wx.hideLoading();
        that.setData({
          'img': res.tempFilePath

        });
        console.log('ok');
      },
      fail: function (res) {
        wx.hideLoading();
        wx.showToast({
          icon: 'none',
          title: '生成失败!',
        });
      }
    })
  },

 

完整demo源码下载地址:https://download.youkuaiyun.com/download/lmx15063393957/11259093

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值