需求
1.生成微信小程序自定義參數二維碼
2.將二維碼拼接背景圖生成活動海報保存至相冊
效果圖
文末已發(fā)布代碼哪怔,有需要請自行獲取,如若有問題歡迎交流
開發(fā)環(huán)境
服務端:php
客戶端:uniapp
應用場景:微信小程序
問題
1.怎么生成微信小程序二維碼?
2.怎么生成活動海報?
生成小程序二維碼-服務端
第一步 獲取微信小程序 access_token
https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=?&secret=?
請求方式:POST
請求參數:
appid 微信小程序id
secret 微信小程序密鑰
請求返回:
buffer 小程序二維碼二維數組
微信官方文檔.小程序-獲取AccessToken
第二步 獲取二維碼 Buffer
https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token=ACCESS_TOKEN
請求方式:POST
請求參數:
scene 二維碼參數
page 二維碼打開路徑
請求返回:
buffer 小程序二維碼二維數組
微信官方文檔.小程序-獲取二維碼
第三步 將buffer轉換為base64字節(jié)碼
微信小程序無法直接將buffer保存到圖片,所以最好將其轉換為base64字節(jié)碼诫咱,通過轉換為base64字節(jié)碼寫入到畫布,通過保存畫布到相冊洪灯,即可實現保存海報
客戶端
創(chuàng)建活動海報
UI代碼
<template>
<view class="container">
<view class="contents">
<canvas class="page-content" canvas-id="shareCanvas" style="width:100%;" :style="{ height: height + 'px' }"></canvas>
</view>
<view class="page-bottom flex text-center">
<button class="cu-btn block bg-orange" @tap="selectImage">選擇圖片</button>
<button class="cu-btn block bg-orange" @tap="saveImage">保存圖庫</button>
</view>
</view>
</template>
獲取二維碼
const url ="服務器接口地址";
//加載頁面參數
let scene = 'id=' + this.id + '&token=' + this.token + '&type=1';
let params={
page: 'pages/index/index',
scene: scene
}
uni.request({
url: url,
data: params,
method: "POST",
header: {
"Content-Type": "application/x-www-form-urlencoded"
},
dataType: 'arraybuffer',//請求字節(jié)
success: (res) => {
//獲取base64 字符串
var data=res.data;
//拼裝base64圖片
var img='data:image/png;base64,'+data;
//調起繪制器
this.initImage(img);
}
});
*注意事項:
1.由于從微信官方請求下來的圖片字節(jié)碼不帶base64數據頭坎缭,需要自行拼接,如:
var img='data:image/png;base64,'+data;
2.由于全部為字節(jié)碼建議dataType設置為arraybuffer签钩,這樣可以避免請求亂碼
繪制畫布
uni.getSystemInfo({
success: function(e) {
console.log(e);
//獲取屏幕寬高設置畫布寬高
let width = e.windowWidth;
let height= e.screenHeight;
that.height=height;
let topheight = 320;//圖片距離上邊距離
const ctx = uni.createCanvasContext('shareCanvas');
// 底圖
ctx.drawImage(res[0].path, 0, 0, width, height);
//繪制序列從上到下掏呼, 通過距離上邊高度來排列顯示
// 文字內容
ctx.setTextAlign('center'); // 文字居中
ctx.setFillStyle('#F0AD4E'); // 文字顏色:黑色
ctx.setFontSize(22); // 文字字號:22px
ctx.fillText('雙十一活動', width / 2, topheight-30);
ctx.setFillStyle('#FFFFFF');
ctx.setFontSize(20);
ctx.fillText('掃碼領取更多獎', width / 2, topheight);
// 小程序碼
const qrImgSize = 140;
ctx.drawImage(res[1], (width - qrImgSize) / 2, topheight+15 , qrImgSize, qrImgSize);
ctx.stroke();
ctx.draw();
}
});
*注意事項:
1.畫布組件顯示內容為圖層,所以為了鋪墊元素铅檩,需要注意從上到下元素的間距憎夷。
保存到相冊
const wxCanvasToTempFilePath = tools.promisify(uni.canvasToTempFilePath);
const wxSaveImageToPhotosAlbum = tools.promisify(uni.saveImageToPhotosAlbum);
wxCanvasToTempFilePath(
{
canvasId: 'shareCanvas'
},
this
).then(res => {
return wxSaveImageToPhotosAlbum({
filePath: res.tempFilePath
});
})
.then(res => {
wx.showToast({
title: '已保存到相冊'
});
});