最近开始做微信小程序,有这样一个需求
从列表页进入详情,在每一个详情页面去分享,分享出来的图片是带有当前详情数据的图片
如下图的列表
分享出来的样子
解决方案和思路canvas画图生成图片
上代码
【html部分】
<canvas style='width:{{canvasWidth}}px;height:{{canvasHeight}}px' canvas-id='myCanvas'></canvas>
<button open-type='share'>分享</button>
【js部分】
var ctx = "" // 用于获取canvas
var leftMargin = "" //文字距离左边边距
var Margin = "" //文字距离右边边距
Page({
/
页面的初始数据
/
data: {
title: '人人车司机',
salary: '500-8000元/月',
rtype: '日结',
rmoney: '20元',
canvasWidth: '', // canvas宽度
canvasHeight: '', // canvas高度
imagePath: '' // 分享的图片路径
},
/
生命周期函数--监听页面加载
/
onLoad: function (options) {
var that = this
var sysInfo = wx.getSystemInfo({
suess: function (res) {
that.setData({
//设置宽高为屏幕宽,高为屏幕高的80%,因为文档比例为5:4
canvasWidth: res.windowWidth,
canvasHeight: res.windowWidth 0.8
})
leftMargin = res.windowWidth
Margin = res.windowWidth 0.8
},
})
},
/
生命周期函数--监听页面初次渲染完成
/
onReady: function () {
ctx = wx.createCanvasContext('myCanvas')
this.addImage()
this.tempFilePath()
},
//画背景图
addImage: function () {
var context = wx.createContext();
var that = this;
var path = "/images/share.jpg";
//将模板图片绘制到canvas,在开发工具中drawImage()函数有问题,不显示图片
//不知道是什么原因,手机环境能正常显示
ctx.drawImage(path, 0, 0, this.data.canvasWidth, this.data.canvasHeight);
this.addTitle()
this.addRtype()
this.addRmoney()
this.addSalary()
ctx.draw()
},
//画标题
addTitle: function (){
var str = this.data.title
ctx.font = 'normal bold 20px sans-serif';
ctx.setTextAlign('center'); // 文字居中
ctx.setFillStyle("#222222");
ctx.fillText(str, this.data.canvasWidth/2,65)
},
// 画返费方式
addRtype: function () {
var str = this.data.rtype
ctx.setFontSize(16)
ctx.setFillStyle("#ff4200");
ctx.setTextAlign('left');
ctx.fillText(str, leftMargin 0.35, Margin 0.4)
},
// 画返费金额
addRmoney: function () {
var str = this.data.rmoney
ctx.setFontSize(16)
ctx.setFillStyle("#222");
ctx.setTextAlign('left');
ctx.fillText(str, leftMargin 0.35, Margin 0.5)
},
// 画薪资
addSalary: function () {
var str = this.data.salary
ctx.setFontSize(16)
ctx.setFillStyle("#222");
ctx.setTextAlign('left');
ctx.fillText(str, leftMargin 0.35, Margin 0.61)
},
/
用户点击右上角分享
/
onShareAppMessage: function (res) {
// return eventHandler接收到的分享参数
return {
title: this.data.title,
path: '/pages/test/test',
imageUrl: this.data.imagePath
};
},
//导出图片
tempFilePath: function(){
let that = this;
wx.canvasToTempFilePath({
canvasId: 'myCanvas',
suess: function suess(res) {
wx.saveFile({
tempFilePath: res.tempFilePath,
suess: function suess(res) {
that.setData({
imagePath: res.savedFilePath
});
}
});
}
});
},
/
生命周期函数--监听页面显示
/
onShow: function () {
},
/
生命周期函数--监听页面隐藏
/
onHide: function () {
},
/
生命周期函数--监听页面卸载
/
onUnload: function () {
},
/
页面相关事件处理函数--监听用户下拉动作
/
onPullDownRefresh: function () {
},
/
页面上拉触底事件的处理函数
/
onReachBottom: function () {
}
})
为大家推荐现在关注度比较高的微信小程序教程一篇长沙网络推广为大家精心整理的,希望喜欢。
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持狼蚁SEO。