欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

微信小程序绘制canvas图片

程序员文章站 2024-02-11 17:14:28
...

1.效果图

微信小程序绘制canvas图片

2.注意事项

1.https网址图片需要预先下载到本地用wx.downloadFile方法
2.wx.downloadFile需要在微信公众号后台配置域名才能获取图片,如图:

微信小程序绘制canvas图片

3.代码

1.wxml

canvas.wxml

<cover-view bindtap='savePic'>
        <canvas style="width:100%;height:{{contentHeight}}px"   canvas-id="myCanvas" bindlongpress="savePic"> 
            
            
        </canvas>
  </cover-view>
  <button bindtap='savePic' class="buttonStyle">预览并发送</button>

2.js代码

  1.图片需要先下载到本地,并保存本地图片路径,包括头像,头像图片的域名同样要在后台配置,不然发布线上获取不到。
canvas.js

var util = require('../../utils/md5.js');
var tool = require('../../utils/base64tool.js')
var app = new getApp();

//canvas.js
Page({
  data: {
    windowWidth: 0, //屏幕宽度
    windowHeight: 0,//屏幕高度
    contentHeight: 0,//内容高度
    thinkList: [], //文字超出换行处理
    lineHeight: 30, //固定值
    contentTitle: "我的昵称", //我的昵称
    canvasUrl: "", //canvasurl
    qrCode: "", //小程序码https图片路径
    goodsInfoImg: "",  //海报图片
    specText: "京东社交电商合作伙伴", //京东社交电商合作伙伴
    userIcon:""//微信头像
  },

  onLoad: function (options) {

    let that = this;

    that.getQr();
    // 查看是否授权
    wx.getSetting({
      success(res) {
        if (res.authSetting['scope.userInfo']) {
          // 已经授权,可以直接调用 getUserInfo 获取头像昵称
          wx.getUserInfo({
            success(resInfo) {
              that.setData({ contentTitle: resInfo.userInfo.nickName})
              wx.downloadFile({
                url: resInfo.userInfo.avatarUrl,
                success(downloadRes) {
                  if (downloadRes.statusCode === 200) {
                    that.setData({
                      userIcon: downloadRes.tempFilePath
                    })
                  }
                }
              })
            }
          })
        } else {
          that.setData({
            userIcon: '/img/noperson.png'
          })
        }
      }
    })

  





   






    //获取设备信息高度。计算出其他的高度等
    wx.getSystemInfo({
      success: function (res) {
        that.setData({
          windowWidth: res.windowWidth,
          windowHeight: res.windowHeight,
          normalPageX:
            res.windowWidth * 0.045, //左边文本图片X轴位置
          boxWidth: res.windowWidth * 0.91, //分享图片box宽度
          boxheight: res.windowHeight, //分享图片box高度
          boxPageY: res.windowWidth * 0.2, //boxY轴位置
          imgWidth: res.windowWidth * 0.91, //海报图片宽度
          imgHeight: res.windowHeight * 0.82, //海报图片高度
          imgPageY: res.windowWidth * 0, //海报图片Y轴位置
          userIconWidth: res.windowWidth * 0.162,//头像图片宽度
          userIconHeight: res.windowWidth * 0.162,//头像图片高度
          userIconPageY: res.windowHeight * 0.82 + 15,//头像Y轴位置
          codeWidth: res.windowWidth * 0.25, //小程序码图片宽度
          codeHeight: res.windowWidth * 0.25, //小程序码图片高度
          codePageY: res.windowHeight * 0.80, //小程序码Y轴位置
          avatarPageY: res.windowHeight * 0.82 + 15, //头像Y轴位置
          titlePageY: res.windowHeight * 0.82 + 25, //微信昵称Y轴位置
          specPageY: res.windowHeight * 0.82 + 42, //京东社交Y轴位置
        });
      }
    });
    //网络图片转为本地图片,直接显示网络图片的话真机不显示
   // that.getTempFile("cloud://luer-f3ipn.6c75-luer-f3ipn-1301025398/6684e5652d611c27b5895a6911e51b7.png");
    that.getTempFile(app.globeData.shareCodeImg); 
  },
//获取小程序码
  getQr: function () {
    var that = this;
    var phone = wx.getStorageSync('phone');
    var apiKey = 'aaa@qq.com¥%GFYLCL#*WLMinPro!!;';
    var time = Date.parse(new Date());
    var sign = util.hexMD5(apiKey + time);
    apiKey = util.hexMD5(apiKey);
    var url = app.globeData.host + 'minPro/getShareMinCode?sign=' + sign + '&apiKey=' + apiKey + '&time=' + time + '&phone=' + phone;
    that.setData({
      qrCode: url
    })
  },



  //临时图片路径
  getTempFile: function (url) {
    wx.showLoading({
    });
    let that = this;
    wx.cloud.downloadFile({
      fileID: url,
      success: function (res) {
        console.log("res.tempFilePath===>", res.tempFilePath)
        that.setData({
          goodsInfoImg: res.tempFilePath
        });
        //继续生成商品的小程序码
        that.downloadSkuQrCode(that.data.qrCode);
      },
      fail: function (err) { }
    });
  },
  getData: function () {
    let that = this;

    let i = 0;
    let lineNum = 1;
    let thinkStr = "";
    let thinkList = [];
    for (let item of that.data.contentTitle) {
      if (item === "\n") {
        thinkList.push(thinkStr);
        thinkList.push("a");
        i = 0;
        thinkStr = "";
        lineNum += 1;
      } else if (i === 21) {
        thinkList.push(thinkStr);
        i = 1;
        thinkStr = item;
        lineNum += 1;
      } else {
        thinkStr += item;
        i += 1;
      }
    }
    thinkList.push(thinkStr);
    that.setData({
      thinkList: thinkList
    });
    that.createNewImg(lineNum);
  },

  //画矩形,也是整块画布的大小,宽度是屏幕宽度,高度根据内容多少来动态设置。
  drawSquare: function (ctx, height) {
    let that = this;
    ctx.rect(
      that.data.windowWidth * 0.045,
      that.data.boxPageY,
      that.data.boxWidth,
      height
    );
    ctx.setFillStyle("#fff");
    ctx.fill();
  },

  // 设置文字大小,并填充颜色。
  drawFont: function (ctx, contentTitle, height) {
    let that = this;
    let str = that.data.contentTitle;
    let firstline;
    let secondline;
    //一行显示12个字,超过一行时
    if (str.length > 11) {
      //第一行截取前14个字符
      firstline = str.substring(0, 11);
    } else {
      //一行就能显示时候
      firstline = str;
    }
    //填充微信昵称
    ctx.setFontSize(14);
    ctx.setFillStyle("#000");
    ctx.fillText(firstline, that.data.normalPageX + that.data.userIconWidth+20, that.data.titlePageY+10);

    //填充京东社交合作伙伴
    if (that.data.specText) {
      ctx.setFontSize(12);
      ctx.setFillStyle("#999999");
      ctx.fillText(
        that.data.specText,
        that.data.normalPageX + that.data.userIconWidth+20,
        that.data.specPageY + 18
      );
    }
  },
  // 根据文字多少动态计算高度,然后依次画出矩形,文字,横线和小程序码。
  createNewImg: function (lineNum) {
    let that = this;
    let ctx = wx.createCanvasContext("myCanvas");
    let contentHeight = that.data.boxheight;
    that.drawSquare(ctx, contentHeight);
    that.setData({
      contentHeight: contentHeight
    });
    let height = 100;
    for (let item of that.data.thinkList) {
      if (item !== "a") {
        that.drawFont(ctx, item, height);
        height += that.data.lineHeight;
      }
    }
    //海报图片
    ctx.drawImage(
      that.data.goodsInfoImg,
      that.data.normalPageX,
      that.data.imgPageY,
      that.data.imgWidth,
      that.data.imgHeight
    );

   //画圆形
    ctx.save();
    ctx.beginPath(); //开始绘制
    ctx.arc(that.data.userIconWidth / 2 + 28, that.data.userIconWidth / 2 + that.data.userIconPageY, that.data.userIconWidth / 2, 0, Math.PI * 2, false);
    ctx.clip();
    //头像
    ctx.drawImage(
      that.data.userIcon,
      that.data.normalPageX+10,
      that.data.userIconPageY,
      that.data.userIconWidth,
      that.data.userIconHeight
    );
    ctx.restore();
    // 填充小程序码
    ctx.drawImage(
      that.data.qrCode,
      that.data.normalPageX + that.data.windowWidth * 0.65,
      that.data.codePageY,
      that.data.codeWidth,
      that.data.codeHeight
    );
    // 长按分享给好友
    ctx.setFillStyle("#333");
    ctx.font = "normal normal 9px sans-serif";
    ctx.fillText(
      "长按分享",
      that.data.normalPageX +
      that.data.windowWidth * 0.65 +
      that.data.codeWidth/3,
      that.data.codePageY + that.data.codeWidth + 10
    );
    ctx.draw(); //绘制到canvas
  },

  // 保存图片
  savePic: function () {
    let that = this;
    wx.canvasToTempFilePath({
      x: 0,
      y: 50,
      width: that.data.windowWidth * 2,
      height: that.data.contentHeight * 2,
      canvasId: "myCanvas",
      success: function (res) {
        // util.savePicToAlbum(res.tempFilePath);
        wx.hideLoading();
        var tempFilePath = res.tempFilePath;
        that.setData({
          canvasUrl: tempFilePath
        });
        if (tempFilePath !== "") {
          wx.hideLoading();
          wx.previewImage({
            current: that.data.canvasUrl, // 当前显示图片的http链接
            urls: [that.data.canvasUrl], // 需要预览的图片http链接列表
            success: function (_res) {
              console.log("预览成功啦");
            }
          });
        }
      }
    });
  },
  //下载小程序码
  downloadSkuQrCode: function (url) {
    let that = this;
    wx.downloadFile({
      url: url,
      success: function (res) {
        that.setData({
          qrCode: res.tempFilePath
        });
        wx.hideLoading();
        //生成数据
        that.getData();
      },
      fail: function (err) {
        wx.showToast({
          title: "下载小程序码失败,稍后重试!",
          icon: "none",
          duration: 5000
        });
      }
    });
  },

  //点击保存到相册
  saveShareImg: function () {
    var that = this;
    wx.showLoading({
      title: '正在保存',
      mask: true,
    })
    setTimeout(function () {
      wx.canvasToTempFilePath({
        canvasId: 'myCanvas',
        success: function (res) {
          wx.hideLoading();
          var tempFilePath = res.tempFilePath;
          wx.saveImageToPhotosAlbum({
            filePath: tempFilePath,
            success(res) {
              // utils.aiCardActionRecord(19);
              wx.showModal({
                content: '图片已保存到相册,赶紧晒一下吧~',
                showCancel: false,
                confirmText: '好的',
                confirmColor: '#333',
                success: function (res) {
                  if (res.confirm) { }
                },
                fail: function (res) { }
              })
            },
            fail: function (res) {
              wx.showToast({
                title: res.errMsg,
                icon: 'none',
                duration: 2000
              })
            }
          })
        }
      });
    }, 1000);
  }
});