手机系统为IOS,通过分享图片入口进入小程序后或者是打开调试模式时;样式会正常。
async generatePoster() {
this.createSelectorQuery()
.select('#myPoster')
.fields({ node: true, size: true })
.exec(async (res) => {
// Canvas 对象
const canvas = res[0].node
// 渲染上下文
const ctx = canvas.getContext('2d')
// Canvas 画布的实际绘制宽高
const width = res[0].width
const height = res[0].height
// 初始化画布大小
const dpr = wx.getWindowInfo().pixelRatio
canvas.width = width * dpr
canvas.height = height * dpr
// Canvas转临时图片路径
wx.canvasToTempFilePath({
canvas: canvas, // 指定要转换的Canvas实例
x: 0, // 裁剪起始x坐标,0表示从画布最左端开始
y: 0, // 裁剪起始y坐标,0表示从画布最上端开始
width: width, // 裁剪宽度,使用实际绘制宽度
height: height, // 裁剪高度,使用实际绘制高度
// 调整输出尺寸,避免图片过大导致分享菜单样式错乱
// 分享图片建议尺寸:宽度不超过800px,高度按比例计算
destWidth: Math.min(width * dpr, 800), // 限制输出宽度,最大800px
destHeight: Math.min(height * dpr, Math.round((800 * height) / width)), // 按比例计算输出高度
fileType: 'png', // 输出文件类型,png格式压缩率高,质量好
quality: 1, // 适当降低质量,平衡清晰度和文件大小
success: (res: any) => {
this.setData({
posterPath: res.tempFilePath
})
},
fail: (err: any) => {
console.error('Canvas转临时图片失败:', err)
wx.showToast({
title: '生成图片失败',
icon: 'none'
})
},
complete: () => {
// 隐藏加载
wx.hideLoading()
}
})
})
},
//分享方法
async share() {
wx.showLoading({
title: '分享中...',
mask: true
})
const fs = wx.getFileSystemManager()
const persisterPath = `${wx.env.USER_DATA_PATH}/share_${Date.now()}.png`
fs.copyFileSync(this.data.posterPath, persisterPath)
setTimeout(() => {
wx.hideLoading()
wx.showShareImageMenu({
path: persisterPath,
success: (res) => {
console.log(res)
},
complete: () => {}
})
}, 500)
}

这api bug真多