微信小程序canvas绘图 绘图完成保存图片 附带代码和效果图

640 阅读2分钟

保存图片的页面

微信截图_20220328120008.png

保存下来的图片

SyktTb8q00kO6bbd30050351add8fe8e7af0776727ed.png

以上就是效果图啦, 接下来就是怎么实现它了

首先定义canvas的大小,绘制图片以及文字的布局

将canvas内容生成图片并保存到相册和本地

上代码啦!!自行解析

wxml

<nav-bar navbar-data='{{nvabarData}}'></nav-bar>
<view class="zan_dialog__mask" bindtap="toggleDialog"></view>
<canvas canvas-id="myCanvas" style='width:{{canvasWidth}}px; height:{{canvasHeight}}px; '  disable-scroll='true'/>
 
<button class="shareBtn" bindtap="saveImg">保存图片</button>

wxss

canvas {
    width: 90%;
    height: 860rpx;
    margin: 0 auto;
    margin-top: 20vh;
    z-index: 10;
}
 
.zan_dialog__mask {
    position: fixed;
    width: 100%;
    height: 100%;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    background: rgba(0, 0, 0, 0.2);
    z-index: 9;
}
 
.shareBtn {
    width: 360rpx;
    height: 80rpx;
    font-size: 30rpx;
    color: #fff;
    background-color: #00a1a6;
    font-family: "微软雅黑";
    border-radius: 40rpx;
    margin-top: 60rpx;
    z-index: 10;
 
}
/* 用户看到的页面 */

js


var api = require('../../utils/api.js');
var util = require('../../utils/util.js');
const app = getApp()
Page({
 
  /**
   * 页面的初始数据
   */
  data: {
    nvabarData: {
      showCapsule: 1, //是否显示左上角图标   1表示显示    0表示不显示
      title: '点亮城市', //导航栏 中间的标题
    },
  },
 
 
  /**
   * 生命周期函数--监听页面加载
   * address: "山西大学城"
   */
  
  onLoad: function (options) {
    var that = this;
    var match_id = options.mat_id;
    var energy_num = options.energy_num;
    var nickname = wx.getStorageSync('nickname');
    //获取比赛信息
    var res = util.request(api.getMatchinfo, { match_id: match_id });
    var a = res.then(function (result) {
      if (result.code == 200) {
        that.setData({
          // mat_logo:result.data[0].logo,
          title: result.data[0].title,
          city: result.data[0].city,
          // city_logo: result.data[0].city_logo,
          nickname: nickname,
          energy_num: energy_num
        })
        // 比赛logo图网络图片处理
        wx.downloadFile({
          url: result.data[0].city_logo,
          success: function (res) {
            that.setData({
              mat_logo: res.tempFilePath
            })
            //调用二维码图
            var res = util.request(api.setqrCode, { match_id: match_id, type: 2 });
            var a = res.then(function (result) {
              wx.downloadFile({
                url: result.path,
                success: function (res) {
                  // console.log(res);return;
                  that.setData({
                    eqcode_img: res.tempFilePath
                  })
                  that.startCanvas()
                }
              })
            })
          }
        })
      }
    })
 
  },
 
 
  startCanvas: function () {
    var that = this;
    var rpx;
    //获取屏幕宽度,获取自适应单位
    wx.getSystemInfo({
      success: function (res) {
        rpx = res.windowWidth / 375;
      },
    })
    const ctx = wx.createCanvasContext('myCanvas')
    var Username = that.data.nickname;//"狂奔的蜗牛";
    var biaoyu = "恭喜您";
    var explain = "在2022年"+that.data.title+"活动中点亮"+that.data.city+",";
    var explaintwo = "为"+that.data.city+"共积攒了"+that.data.energy_num+"能量值"
    // 图片
    ctx.drawImage("../../img/sharebg.png", 0, 0, 340 * rpx, 500 * rpx)
    // 文本
    ctx.setFillStyle('#fff')//文字颜色:默认黑色
    ctx.setFontSize(18 * rpx)//设置字体大小,默认10
    ctx.fillText(Username, 20 * rpx, 30 * rpx)//绘制文本
    ctx.setFontSize(14 * rpx)//设置字体大小,默认10
    ctx.fillText(biaoyu, 120 * rpx, 30 * rpx)//绘制文本
 
    ctx.setFillStyle('#e1e1e1')
    ctx.fillRect(10 * rpx, 50 * rpx, 320 * rpx, 1 * rpx)
 
    ctx.setFillStyle('#fff')
    ctx.setFontSize(12 * rpx)
    ctx.fillText(explain, 20 * rpx, 75 * rpx)
    ctx.fillText(explaintwo, 20 * rpx, 92 * rpx)
 
 
    ctx.setFillStyle('#ffffff')
    ctx.fillRect(75 * rpx, 110 * rpx, 180 * rpx, 185 * rpx)
 
    ctx.drawImage(that.data.mat_logo, 75 * rpx, 110 * rpx, 180 * rpx, 185 * rpx)
    ctx.drawImage(that.data.eqcode_img, 260 * rpx, 340 * rpx, 60 * rpx, 60 * rpx)
    //调用draw()开始绘制
    ctx.draw()
 
    //将生成好的图片保存到本地,需要延迟一会,绘制期间耗时
    setTimeout(function () {
      wx.canvasToTempFilePath({
        canvasId: 'myCanvas',
        success: function (res) {
          var tempFilePath = res.tempFilePath;
          that.setData({
            loadImagePath: tempFilePath,
          });
        },
        fail: function (res) {
          console.log(res);
        }
      });
    }, 500);
 
  },
 
 
  //点击保存到相册
  saveImg: function () {
    wx.saveImageToPhotosAlbum({
      filePath: this.data.loadImagePath,
      success(res) {
        console.log('res', res);
        wx.showToast({
          title: '已保存到相册',
          icon: 'success',
          duration: 3000
        })
        util.redirect('pages/tree/tree');
      }, fail: function (err) {
        if (err.errMsg === "saveImageToPhotosAlbum:fail:auth denied" || err.errMsg === "saveImageToPhotosAlbum:fail auth deny" || err.errMsg === "saveImageToPhotosAlbum:fail authorize no response") {
          wx.openSetting({
            success(settingdata) {
              console.log(settingdata)
              if (settingdata.authSetting['scope.writePhotosAlbum']) {
                wx.showToast({
                  title: '获取权限成功,再次点击保存图片',
                  icon: 'none',
                  duration: 1500
                })
                console.log('获取权限成功,给出再次点击图片保存到相册的提示。')
              } else {
                console.log('获取权限失败,给出不给权限就无法正常使用的提示')
              }
            }
          })
        }
      },
      complete(res) {
        wx.hideLoading()
      }
    })
  },
 
})

到这里就结束啦,也是第一次接触canvas 大佬们有什么补充和建议留言就好哦