小程序轉(zhuǎn)發(fā),圖片不配置會自動截取頂部頁面史飞。如配置圖片尖昏,比例不為5:4則會截取圖片頂部內(nèi)容。
為使自定義圖片完整展示构资,做了以下操作抽诉。
wxml
<!-- width設(shè)置了canvasW,height設(shè)置了canvasH,換過其他值吐绵,好像有影響迹淌,background無效 -->
<canvas style="position: absolute; top: -1000px; left: -1000px; width: 875px; height: 700px; background: #fff;" canvas-id="canvas"></canvas>
js
onShareAppMessage: async function() {
let imgUrl = 'xxxxx'
return {
title: '分享',
path: `/pages/index/index`,
imageUrl: await cutShareImg(imgUrl)
}
}
方法
const cutShareImg = (imgUrl) => {
return new Promise((resolve) => {
wx.getImageInfo({
src: imgUrl, // 原圖路徑
success: (res) => {
let ctx = wx.createCanvasContext("canvas")
let canvasW = 0
let canvasH = res.height
// 把比例設(shè)置為 寬比高 5:4
canvasW = (res.height * 5) / 4
// 為畫框設(shè)置背景色,注意要放在畫圖前己单,圖會覆蓋在背景色上
ctx.fillStyle = "#fff"
ctx.fillRect(0, 0, canvasW, canvasH)
// ctx.drawImage(res.path, (res.width - canvasW) / 2, 0, canvasW, canvasH, 0, 0, canvasW, canvasH)
ctx.drawImage(
res.path,
0,
0,
canvasW,
canvasH,
(canvasW - res.width) / 2, // 寬度從中間向兩邊填充
0,
canvasW,
canvasH
)
ctx.draw(false, () => {
wx.canvasToTempFilePath({
width: canvasW,
height: canvasH,
destWidth: 750, // 標(biāo)準(zhǔn)的iphone6尺寸的兩倍唉窃,生成高清圖
destHeight: 600,
canvasId: "canvas",
fileType: "jpg", // 注意jpg默認(rèn)背景為透明
success: (res) => {
// 設(shè)置分享圖片路徑
resolve(res.tempFilePath)
},
})
})
}
})
})
}
export default {
cutShareImg,
}
注:
1.jpg,png背景色,png支持透明色
2.異步方法纹笼,最好是在進(jìn)入頁面就調(diào)用纹份,否則需要await才行
3.注意canvas的寬高