在开发微信小程序的过程中免不了要使用到分享功能,然而现在微信官方还没有开放小程序分享到朋友圈的功能,这时候我们只能使用其他方法分享到朋友圈了。
效果图如下:
组件文件:
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} //二维码大小
})