微信小程序生成海報(bào)并保存到本地(附帶二維碼生成)

小程序端剛剛拿到了一個新的需求說要生成一張海報(bào) 用戶保存圖片到本地分享,話不多說直接上代碼

/ pages/haibao/haibao.js
Page({
 
  /**
   * 頁面的初始數(shù)據(jù)
   */
  data: {
    evalatImage:'',
    bgBanner:'',
    imagePath:"",
    maskHidden:false,
    qrcode_image:''
  },
 
  /**
   * 生命周期函數(shù)--監(jiān)聽頁面加載
   */
  onLoad: function (options) {
 
  },
 
  /**
   * 生命周期函數(shù)--監(jiān)聽頁面初次渲染完成
   */
  onReady: function () {
 
  },
 
  /**
   * 生命周期函數(shù)--監(jiān)聽頁面顯示
   */
  onShow: function () {
    var  that = this;
    wx.getImageInfo({
      src: "https://m.xinjuenet.com/images/banner/b-xldh.jpg",
      success(res) {
        console.log("banner臨時(shí)路徑:" + res.path);
        that.setData({
          evalatImage: res.path
        })
      }
    })
    wx.getImageInfo({
      src: "https://m.xinjuenet.com/images/banner/b-xldh.jpg",
      success(res) {
        console.log("海報(bào)底部背景:" + res.path);
        that.setData({
          bgBanner: res.path
        })
      }
    })
    that.qrcode_image();
    wx.getImageInfo({
      src: that.data.qrcode_image,
      success(res) {
        console.log("二維碼:" + res.path);
        that.setData({
          qrcode_image: res.path
        })
      }
    })
  },
 
  /**
   * 生命周期函數(shù)--監(jiān)聽頁面隱藏
   */
  onHide: function () {
 
  },
 
  /**
   * 生命周期函數(shù)--監(jiān)聽頁面卸載
   */
  onUnload: function () {
 
  },
 
  /**
   * 頁面相關(guān)事件處理函數(shù)--監(jiān)聽用戶下拉動作
   */
  onPullDownRefresh: function () {
 
  },
 
  /**
   * 頁面上拉觸底事件的處理函數(shù)
   */
  onReachBottom: function () {
 
  },
 
  /**
   * 用戶點(diǎn)擊右上角分享
   */
  onShareAppMessage: function () {
 
  },
  //點(diǎn)擊生成海報(bào)
  formSubmit: function (e) {
    var that = this;
    wx.showToast({
      title: '海報(bào)生成中...',
      icon: 'loading',
      duration: 1000
    });
    that.createNewImg();
    setTimeout(function () {
      wx.hideToast()
      that.setData({
        maskHidden: true
      });
    }, 1000);
  },
  //將canvas轉(zhuǎn)換為圖片保存到本地,然后將圖片路徑傳給image圖片的src
  createNewImg: function () {
    var that = this;
    var context = wx.createCanvasContext('mycanvas');
    context.clearRect(0, 0, 375, 660);
    context.setFillStyle("#fff")
    context.fillRect(0, 0, 375, 660)
    context.save();
 
    var path = that.data.evalatImage;
    context.drawImage(path, 0, 0, 375, 183);
 
 
    var path1 = that.data.bgBanner;
    console.log("海報(bào)底部背景圖" + path1);
    var path2 = that.data.qrcode_image;
    console.log("海報(bào)底部二維碼" + path2);
    context.setFontSize(16);
    context.setFillStyle('#333');
    context.setTextAlign('left');
    context.fillText("測試結(jié)果", 60, 230);
    context.stroke();
    context.save();
 
    var titl = "分享標(biāo)題";
    context.setFontSize(18);
    context.setFillStyle('#333');
    context.setTextAlign('left');
    context.font = 'normal bold 18px sans-serif';
    context.fillText(titl, 60, 270);
    context.stroke();
    context.save();
 
 
 
    context.setFontSize(16);
    context.setFillStyle('#333');
    context.setTextAlign('left');
    context.fillText("測試說明", 60, 320);
    context.stroke();
    context.save();
    context.drawImage(path1, 0, 550, 375, 130);
 
    var results = "分享的文本信息,布上下文 canvasID";
 
    // 測試結(jié)果說明
    that.dealWords({
      ctx: context,                     //畫布上下文 canvasID
      fontSize: 16,                //字體大小
      word: results,                  //需要處理的文字
      maxWidth: 270,             //一行文字最大寬度
      x: 60,                    //文字在x軸要顯示的位置
      y: 340,                      //文字在y軸要顯示的位置
      maxLine: 6              //文字最多顯示的行數(shù)
    });
    context.stroke();
    context.save(); //保存之前的畫布設(shè)置
 
    //繪制頭像
    context.beginPath();
    context.arc(50, 225, 5, 0, 2 * Math.PI);
    context.setStrokeStyle("#c7eddd");
    context.setFillStyle("#44bf8c");
    context.clip(); //裁剪上面的圓形
    context.fill();//填充
    context.restore();//因?yàn)閏lip是剪切了畫布  則后面所有的操作都會限制在被裁減的區(qū)域內(nèi)可見  用restore可以恢復(fù)之前的設(shè)置
    context.closePath();
 
    context.save(); //保存之前的畫布設(shè)置
    context.beginPath();
    context.arc(50, 315, 5, 0, 2 * Math.PI);
    context.setStrokeStyle("#c7eddd");
    context.setFillStyle("#44bf8c");
    context.clip(); //裁剪上面的圓形
    context.fill();//填充
    context.restore();
    context.closePath();
 
    context.save(); //保存之前的畫布設(shè)置
    context.beginPath();
    context.arc(55, 610, 50, 0, 2 * Math.PI);
    context.setStrokeStyle("#ffe200");
    context.clip(); //裁剪上面的圓形
    context.drawImage(path2, 5, 560, 100, 100);
    context.restore();
    context.closePath();
 
    context.save(); //保存之前的畫布設(shè)置
    context.beginPath();
    // context.setFontSize(16);
    context.setFillStyle('#fff');
    context.setTextBaseline("top");
    context.setTextAlign('left');
    // context.font = 'normal 18px arial';
    // context.fillText("預(yù)防疫情四大宅家心理健康測評", 115, 565);
    // context.fillText("預(yù)防疫情四大宅家心理健康測評", 115, 589);
    that.dealWords({
      ctx: context,                     //畫布上下文 canvasID
      fontSize: 16,                //字體大小
      word: titl,                 //需要處理的文字
      maxWidth: 240,             //一行文字最大寬度
      x: 115,                   //文字在x軸要顯示的位置
      y: 540,                      //文字在y軸要顯示的位置
      maxLine: 2              //文字最多顯示的行數(shù)
    });
    context.stroke();
    context.closePath();
    context.save(); //保存之前的畫布設(shè)置
    context.draw(true);//true表示保留之前繪制內(nèi)容
 
 
    //將生成好的圖片保存到本地,需要延遲一會,繪制期間耗時(shí)
    setTimeout(function () {
      wx.canvasToTempFilePath({
        canvasId: 'mycanvas',
        success: function (res) {
          var tempFilePath = res.tempFilePath;
          that.setData({
            imagePath: tempFilePath
          });
        },
        fail: function (res) {
          console.log(res);
        }
      });
    }, 1000);
  },
  //文本換行
  dealWords(options) {
    options.ctx.setFontSize(options.fontSize);//設(shè)置字體大小
    var allRow = Math.ceil(options.ctx.measureText(options.word).width / options.maxWidth);//實(shí)際總共能分多少行
    var count = allRow >= options.maxLine ? options.maxLine : allRow;//實(shí)際能分多少行與設(shè)置的最大顯示行數(shù)比,誰小就用誰做循環(huán)次數(shù)
 
    var endPos = 0;//當(dāng)前字符串的截?cái)帱c(diǎn)
    for (var j = 0; j < count; j++) {
      var nowStr = options.word.slice(endPos);//當(dāng)前剩余的字符串
      var rowWid = 0;//每一行當(dāng)前寬度    
      if (options.ctx.measureText(nowStr).width > options.maxWidth) {//如果當(dāng)前的字符串寬度大于最大寬度,然后開始截取
        for (var m = 0; m < nowStr.length; m++) {
          rowWid += options.ctx.measureText(nowStr[m]).width;//當(dāng)前字符串總寬度
          if (rowWid > options.maxWidth) {
            if (j === options.maxLine - 1) { //如果是最后一行
              options.ctx.fillText(nowStr.slice(0, m - 1) + '...', options.x, options.y + (j + 1) * 25);    //(j+1)*20這是每一行的高度        
            } else {
              options.ctx.fillText(nowStr.slice(0, m), options.x, options.y + (j + 1) * 25);
            }
            endPos += m;//下次截?cái)帱c(diǎn)
            break;
          }
        }
      } else {//如果當(dāng)前的字符串寬度小于最大寬度就直接輸出
        options.ctx.fillText(nowStr.slice(0), options.x, options.y + (j + 1) * 25);
      }
    }
  },
  //點(diǎn)擊保存到相冊
  baocun: function () {
    var that = this
    wx.saveImageToPhotosAlbum({
      filePath: that.data.imagePath,
      success(res) {
        wx.showModal({
          content: '圖片已保存到相冊,趕緊曬一下吧~',
          showCancel: false,
          confirmText: '好的',
          confirmColor: '#333',
          success: function (res) {
            if (res.confirm) {
              console.log('用戶點(diǎn)擊確定');
              /* 該隱藏的隱藏 */
              that.setData({
                maskHidden: false
              })
            }
          }, fail: function (res) {
            console.log(11111)
          }
        })
      }
    })
  },
  qrcode_image: function () {
    let that = this;
    wx.request({
      url: 'https://api.weixin.qq.com/cgi-bin/token',
      data: {
        grant_type: 'client_credential',
        appid: '你的APPID', //不能缺少
        secret: '你的APPID秘鑰' //不能缺少
      },
      success: function (res) {
        wx.request({
          url: 'https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token=' + res.data.access_token,
          data: {
            "path": "pages/index/index", //默認(rèn)跳轉(zhuǎn)到主頁:pages/index/index,可指定
            "width": 200,
            "scene": "type=0&evaId=" + that.data.id,
          },
          responseType: 'arraybuffer', // 這行很重要,轉(zhuǎn)為二進(jìn)制數(shù)組
          header: {
            'content-type': 'application/json;charset=utf-8'
          },
          method: 'POST',
          success(res) {
            //轉(zhuǎn)為base64
            let bin64 = wx.arrayBufferToBase64(res.data);
 
            that.setData({
              //base 64設(shè)置到頁面上
              qrcode_image: "data:image/png;base64," + bin64
            });
          }
        })
      }
    })
  }
})






下面是頁面代碼

<!--pages/haibao/haibao.wxml-->
 
<button bindtap="formSubmit">點(diǎn)擊生成海報(bào)</button>
 
<view class='imagePathBox' hidden="{{maskHidden == false}}">
    <image src="{{imagePath}}" class='shengcheng' ></image>
    <button class='baocun' bindtap='baocun'>點(diǎn)擊保存至相冊,分享到朋友圈</button>
</view>
<view hidden="{{maskHidden == false}}" class="mask"></view> 
<view class="canvas-box">
    <canvas  style="width:375px;height:670px;position:fixed;top:9999px" canvas-id="mycanvas"/>
</view>  

下面也發(fā)一下樣式文件

/* pages/mentality/result/result.wxss */
page{ background:#fff;}
 
 
.imagePathBox{
  width: 100%;
  height: 100%;
  background: rgba(0,0,0,0.7);
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  z-index: 9999;
}
.mask{
  width: 100%;
  height: 100%;
  /* background: rgba(0,0,0,0.7); */
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  z-index: 9000;
}
.shengcheng{
  width: 80%;
  height: 80%;
  position: fixed;
  top: 50rpx;
  left: 50%;
  margin-left: -40%;
  z-index: 10;
}
.baocun{
  display: block;
  width: 80%;
  height: 80rpx;
  padding: 0;
  line-height: 80rpx;
  text-align: center;
  position: fixed;
  bottom: 50rpx;
  left: 10%;
  background: #45be8d;
  color: #fff;
  font-size: 32rpx;
  border-radius: 44rpx;
}
 
.shareFriends{
  display: block;
  width: 80%;
  height: 104rpx;
  padding: 0;
  line-height: 80rpx;
  text-align: center;
  position: fixed;
  bottom: 50rpx;
  left: 10%;
  background: #45be8d;
  color: rgb(211, 208, 208);
  font-size: 32rpx;
  border-radius: 44rpx;
}
 
 
button[class="baocun"]::after{
  border: 0;
}
 
/* canvas繪圖 */
/* .canvas-box{
  width:0rpx;
  height:0rpx;
  overflow: hidden;
  position: fixed;
  left:0rpx;
  bottom:30rpx;
  z-index: 9999;
} */
 

效果圖來一張

image.png
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

友情鏈接更多精彩內(nèi)容