微信小程序实现分享到朋友圈
分享朋友圈现在大家的通用做法就是通过Canvas生成一张图片后进行保存,然后自行转发朋友圈。最近项目有这个需求, 于是就记录一下。(老规矩,我的博客复制粘贴就好使)
如果想要海报上的二维码扫码完直接跳到指定的页面, 那么就需要生成一个带参数的二维码, 你需要看我的另一篇博客:微信小程序生成带参数的二维码以及小程序码
先看一下效果图:
一、先把代码写上去
index.wxml代码:
<view class="container">
<image src="{{shareImage}}" class="share-image"></image>
<canvasdrawer painting="{{painting}}" class="canvasdrawer" bind:getImage="eventGetImage"/>
<button bind:tap="eventDraw">绘制</button>
<button bind:tap="eventSave">保存到本地</button>
</view>
index.wxss代码:
.share-image {
width: 600rpx;
height: 810rpx;
margin: 0 75rpx;
padding: 1px;
margin-top: 40px;
}
button {
margin-top: 100rpx;
}
index.js代码:
Page({
data: {
painting: {},
shareImage: '',
},
onLoad() {
this.eventDraw()
},
eventDraw() {
var that = this;
wx.showLoading({
title: '绘制分享图片中',
mask: true
})
this.setData({
painting: {
width: 375,
height: 568,
clear: true,
views: [
//这个是一个纯白的图片,给整个画布一个白背景,要不然会有马赛克
{
type: 'image',
url: 'https://tjhaizhixian.com/weixin/item/bai.jpg',
width: 375,
height: 568
},
//边框,直接拿了一张图,当做边框
{
type: 'image',
url: 'https://tjhaizhixian.com/weixin/item/biankuang.png',
width: 375,
height: 568
},
//商品图
{
type: 'image',
url: 'https://tjhaizhixian.com/seafood/public/commercial/19/goodsimg/20191014/d4484c7f364078fffad452d2e158636b.jpg',
width: 328,
height: 328,
top:20,
left:22,
},
//商品名称
{
type: 'text',
content: '产品名称产品名称产品名称产品名称产品名称产品名称11111111111111111111111111111111111111111111',
fontSize: 20,
lineHeight: 21,
color: '#000000',
textAlign: 'left',
top: 360,
left: 36,
width: 290,
MaxLineNumber: 2,
breakWord: true,
bolder: true
},
//线条,同样也是用的图
{
type: 'image',
url: 'https://tjhaizhixian.com/weixin/item/xiantiao.png',
width: 325,
height: 5,
top: 443,
left:22
},
//商品价格
{
type: 'text',
content: '¥198.00',
fontSize: 20,
color: '#E62004',
textAlign: 'left',
top: 414,
left: 36,
bolder: true
},
//店铺名称
{
type: 'text',
content: '店铺名称店铺名称',
fontSize: 15,
lineHeight: 21,
color: '#7E7E8B',
textAlign: 'left',
top: 414,
left: 267,
width: 70,
MaxLineNumber: 1,
breakWord: true,
},
// 文字, 打不出这个文字带阴影的效果, 所以也用的图
{
type: 'image',
url: 'https://tjhaizhixian.com/weixin/item/wenzi.png',
width: 145,
height: 75,
top: 460,
left: 36,
},
//二维码
{
type: 'image',
url: 'https://tjhaizhixian.com/Public/Home/images/banner/min_code.jpg',
top: 455,
left: 260,
width: 85,
height: 85
},
]
}
})
},
eventSave() {
wx.saveImageToPhotosAlbum({
filePath: this.data.shareImage,
success(res) {
wx.showToast({
title: '保存图片成功',
icon: 'success',
duration: 2000
})
}
})
},
eventGetImage(event) {
console.log(event)
wx.hideLoading()
const {
tempFilePath,
errMsg
} = event.detail
if (errMsg === 'canvasdrawer:ok') {
this.setData({
shareImage: tempFilePath
})
}
}
})
index.json里面的代码:
{
"navigationBarTitleText": "生成海报",
"usingComponents": {
//在使用页面注册组件(下面有下载地址,如果放的路径不一样,自行就修改为你的路径就行)
"canvasdrawer": "/components/canvasdrawer/canvasdrawer"
}
}
组件下载地址:
链接:https://pan.baidu.com/s/1i9zq01x58p1MdDMVmnz-_Q&shfl=sharepset
提取码:8hrj