在開發微信小程序的過程中免不了要使用到分享功能,然而現在微信官方還沒有開放小程序分享到朋友圈的功能,這時候我們只能使用其他方法分享到朋友圈了。
效果圖如下:
組件文件:
js文件:
// components/rwj-poster/index.js
Component({
/**
* 組件的屬性列表
*/
properties: {
},
/**
* 組件的初始數據
*/
data: {
canvasWidth: 300,
canvasHeight: 400
},
/**
* 組件的方法列表
*/
methods: {
drawPoster: function(options){
let that = this;
let posterWidth = (options.posterSize ? options.posterSize.width:300) || 300;
let posterHeight = (options.posterSize ? options.posterSize.height : 400) || 400;
let qrcodeWidth = (options.qrCodeSize ? options.qrCodeSize.width : 80) || 80;
let qrcodeHeight = (options.qrCodeSize ? options.qrCodeSize.height: 80) || 80;
let qrcodeLeft = (options.qrCodePosition ? options.qrCodePosition.x:110) || 110;
let qrcodeTop = (options.qrCodePosition ? options.qrCodePosition.y: 110) || 110;
let posterUrl = options.backgroundUrl || "";
let qrcodeUrl = options.qrCodeUrl || "";
//注意,用戶畫圖的圖片必須是本地路徑,不能爲網絡路徑
that.setData({
canvasWidth: posterWidth,
canvasHeight: posterHeight
})
that.downloadImage(posterUrl).then((url) => {
posterUrl = url;
that.downloadImage(qrcodeUrl).then((qrUrl) => {
qrcodeUrl = qrUrl;
const ctx = wx.createCanvasContext("canvasPoster", this);
//填充背景圖片
ctx.drawImage(posterUrl, 0, 0, posterWidth, posterHeight);
// 填充小程序碼
ctx.drawImage(qrcodeUrl, qrcodeLeft, qrcodeTop, qrcodeWidth, qrcodeHeight);
// 把canvas圖保存到臨時目錄
ctx.draw(false, function () {
//console.log("繪製完成");
wx.canvasToTempFilePath({
canvasId: "canvasPoster",
success(res) {
//console.log(res);
let url = res.tempFilePath;
that.consolePoster(url);
},
fail: function(res){
//console.log(res);
}
},that);
});
})
})
},
//下載網絡圖片
downloadImage: function (url) {
let that = this;
return new Promise((resolve, reject) => {
if (url.indexOf("http://") > -1 || url.indexOf("https://") > -1) {
wx.downloadFile({
url: url,
success: function (res) {
//console.log(res);
resolve(res.tempFilePath);
},
fail: function () {
reject();
}
})
} else {
resolve(url);
}
})
},
//輸出海報圖臨時路徑
consolePoster: function (url) {
let options = {
url: url
}
this.triggerEvent('getPoster', options);
}
}
})
wxml文件:
<canvas canvas-id="canvasPoster" style="width: {{canvasWidth}}px;height: {{canvasHeight}}px;"></canvas>
使用方式:
在wxml中添加組件
<rwj-poster id="poster" bind:getPoster="getPoster"></rwj-poster>
js中調用畫圖:
this.selectComponent("#poster").drawPoster({
backgroundUrl: "", //圖片地址url,可以爲網絡圖片
qrCodeUrl: "", //圖片地址url,可以爲網絡圖片
posterSize: { width: 300, height: 500 }, //海報大小
qrCodePosition: { x: 80, y: 120 }, //二維碼在圖片中的位置
qrCodeSize: {width: 80, height: 80} //二維碼大小
})