<canvas class="share_canvas" type="2d" id="myCanvas" ></canvas>
onShow() {
let that = this
that.downShareImage()
},
/**
*
* 下载要分享的图片
*/
downShareImage() {
console.log('下载要分享的图片')
const that = this
wx.downloadFile({
url: 'https://img0.baidu.com/it/u=925998594,1358415170&fm=253&fmt=auto&app=138&f=JPEG?w=500&h=281',
success(res) {
// console.log(res.tempFilePath)
that.drawShareImg(res.tempFilePath);
},
fail(error) {
console.log(error)
}
})
},
async drawShareImg(img) {
console.log('又进来了')
let that = this
let {
canvas,
ctx,
} = that.data
const dpr = wx.getSystemInfoSync().pixelRatio
console.log(dpr)
wx.createSelectorQuery().select('#myCanvas')
.fields({
node: true,
size: true
})
.exec((res) => {
canvas = res[0].node
ctx = canvas.getContext('2d')
console.log(res[0])
canvas.width = res[0].width * dpr
canvas.height = res[0].height * dpr
ctx.scale(dpr, dpr)
// 绘制黑色背景
ctx.fillStyle = 'rgba(0, 0, 0, 1)';
ctx.fillRect(0, 0, 462, 343)
let bg = canvas.createImage()
bg.src = '/images/share_bg.png'
bg.onload = () => {
ctx.drawImage(bg, 0, 0, 462, 343);
ctx.restore()
}
let goodimg = canvas.createImage()
goodimg.src = img
goodimg.onload = () => {
ctx.drawImage(goodimg, 250, 80, 150, 150);
ctx.restore()
}
setTimeout(function () {
ctx.font = '14px sans-serif';
ctx.fillStyle = '#000';
let str = '商品名称商品名称商品名称商品名称名称名称'
for (var i = 0; i < str.length; i++) {
if (ctx.measureText(str.substring(0, i + 1)).width > 140) {
ctx.fillText(str.substring(0, i), 60, 98, 140)
ctx.fillText(str.substring(i), 60, 120, 140)
break
}
}
ctx.font = '14px sans-serif';
ctx.fillStyle = '#000';
ctx.fillText('订单金额', 61, 194)
ctx.font = '14px sans-serif';
ctx.fillStyle = '#FBAB2A';
ctx.fillText('¥', 61, 225)
ctx.font = '18px sans-serif';
ctx.fillStyle = '#FBAB2A';
ctx.fillText('899.99', 75, 226)
wx.canvasToTempFilePath({
canvas: canvas,
x: 0,
y: 0,
width: 462,
height: 343,
destWidth: 500,
destHeight: 400,
success: res => {
// 生成的图片临时文件路径
const tempFilePath = res.tempFilePath
console.log('最后生成', tempFilePath)
that.setData({
shareImg: tempFilePath
})
wx.hideToast();
},
fail: (err) => {
wx.hideToast();
}
}, that)
}, 1000)
})
}
onShareAppMessage(e) {
const that = this
return {
title: `向你推荐,商品名称`,
path: "../pages/goods-detail/goods-detail",
imageUrl: that.data.shareImg
}
},