当前页面的js
import Info from"../../utils/util.js";//引入外部js
data: {
hidden: true,
code: "",
title: "",
imgs: "",
imgUrl: "",
sHeight:"",
sWidth:''
},
//请求海报封面和二维码
let that=this;
wx.downloadFile({
url: 'https://test.ydlweb.com/attachment/images/2/2018/12/We2LEFr8J2HFR8JZle2jEc4g742czl.jpg ',
success: (res) => {
that.setData({
imgs: res.tempFilePath
})
}
})
wx.downloadFile({
url: "https://test.ydlweb.com/attachment/images/2/8a6eebb2bb264ef6cae34cf45ca9794b.png",
success: (res) => {
that.setData({
code: res.tempFilePath
})
}
})
//获取设备的宽高,因为canvas中像素是px而不是rpx
let that=this;
wx.getSystemInfo({
success: function (res) {
console.log(res);
that.setData({
sHeight: 912 / 750 * res.screenWidth,//设计稿上面的宽高
sWidth: res.screenWidth
})
setTimeout(() => {
Info.getPhone(that.data.code, that.data.imgs, that.data.sWidth, that.data.sHeight, 'shareImg', 'center', 'red','yellow',)//调用外部封装好的js
},5000)
}
})
//保存海报到手机相册
save: function () {
var that = this
wx.saveImageToPhotosAlbum({
filePath: that.data.imgurl,
success(t) {
wx.showModal({
content: '图片已保存到相册',
showCancel: false,
confirmText: '好的',
success: function (t) {
if (t.confirm) {
console.log('用户确定了');
that.setData({
hidden: true
})
}
},
})
},
fail: function (t) {
console.log("失败", t);
wx.getSetting({
success: function (t) {
t.authSetting["scope.writePhotosAlbum"] || (console.log("进入信息授权开关页面"), wx.openSetting({
success: function (t) {
console.log("openSetting success", t.authSetting);
}
}));
}
});
}
})},
封装好的外部canvas
const getPhone = (code, imgs, sWidth, sHeight, classNames, textStyle, successCallback, textcolor, codecolor )=>{
let that = this;
const variableNum =sWidth / 750;
const ctx = wx.createCanvasContext(classNames);
ctx.drawImage(code, 250 * variableNum, 650 * variableNum, 100, 100); //绘制二维码
ctx.drawImage(imgs, 40, 10, 600 * variableNum, 400 * variableNum); //绘制图片
ctx.setTextAlign(textStyle)
ctx.setFillStyle(codecolor)
ctx.setFontSize(28)
ctx.fillText("我是文字部分....", 400 * variableNum, 500 * variableNum)
ctx.setFillStyle(textcolor)
ctx.fillText("长按二维码....", 400 * variableNum, 600 * variableNum)
ctx.stroke()
ctx.draw();
setTimeout(function () { //这里要加定时器,转成图片需要一定的时间,不然是不出来图片的哦
// canvas画布转成图片
var i = getCurrentPages(), a = i[i.length - 1];//获取当前引用该方法的data里面的值
wx.canvasToTempFilePath({
x: 0,
y: 0,
width: 580,
height: 680,
destWidth: 580,
destHeight: 680,
canvasId: classNames,
fileType: 'png',
success: (res)=>{
console.log(res);
successCallback
a.setData({
imgurl: res.tempFilePath,
hidden: false
})
},
fail: function () {
console.log("保存失败......")
}
})
}, 2000)
}
module.exports = {//将此回调暴露出去
getPhone: getPhone
}
原文:https://blog.csdn.net/weixin_43647163/article/details/87566077