将canvas画布生成图片,并保存到手机相册

wxml:

<canvas 
  canvas-id="gameCanvas" 
  style="width:750rpx; height:350rpx"
  hidden="{{!statusTag}}"
></canvas>

<button bindtap="createImage">生成图片</button>

js

// pages/index/pic.js
Page({

  /**
   * 页面的初始数据
   */
  data: {
    imagePath:'http://imgo2o.shikee.com/goods/2019/10/17/201910171144361688.jpg',  
    imageWidth:'',
    imageHeight:'',
    show:0,
    statusTag:false
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {

  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
    let _this = this,
    deviceWidth = 0;

   //获取设备宽度,用于求所需画在画布上的图片的高度
  wx.getSystemInfo({      
      success:function(res){
        deviceWidth = res.windowWidth;   //获取设备宽度
        wx.getImageInfo({    //获取图片信息
          src: _this.data.imagePath,
          success: function(res){
            let imageWidth = deviceWidth,
              imageHeight = deviceWidth/res.width*res.height;  //求所需画在画布上的图片的高度
            _this.setData({
              'imageWidth': imageWidth,
              'imageHeight':imageHeight
            });
            console.log(imageHeight);
            const ctx = wx.createCanvasContext('gameCanvas');  //创建画布对象  
            ctx.drawImage(_this.data.imagePath, 0, 0, imageWidth, imageHeight);  //添加图片
            ctx.setFontSize(16);      //设置字体大小
            ctx.setFillStyle('blue');   //设置字体颜色
            ctx.fillText('你的名字', imageWidth/2, imageHeight/2);  //设置字体内容、坐标
            ctx.draw();     //开始绘画
          }
        })
      }
    });
  },
  
  createImage: function(){
    this.setData({
      statusTag:true
    })
    let imageWidth = this.data.imageWidth,
      imageHeight = this.data.imageHeight;
      wx.canvasToTempFilePath({     //将canvas生成图片
        canvasId: 'gameCanvas',
        x: 0,
        y: 0,
        width: imageWidth,
        height: imageHeight,
        destWidth: imageWidth,     //截取canvas的宽度
        destHeight: imageHeight,   //截取canvas的高度
        success: function (res) {
          wx.saveImageToPhotosAlbum({  //保存图片到相册
            filePath: res.tempFilePath,
            success: function () {
              wx.showToast({
                title: "生成图片成功!",
                duration: 2000
              })
            }
          })
        }
    })
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})

 

更多详细的功能:https://www.cnblogs.com/gcjun/p/11724531.html

 

H5-canvas生成图片案例:

链接:https://pan.baidu.com/s/1IRiHGeK-X4kC4or0Zj97Gw
提取码:u15s

posted @ 2021-01-06 16:23  小小强学习网  阅读(1549)  评论(0编辑  收藏  举报