2024.09.28 15:23
在很多小程序都用到了生成海报并保存分享的功能,前面也做了一个这样的功能,用了一段时间,感觉还可以,分享并记录一下。
// 绘制海报
const norPoster = (ops) => {
let bg = '', bgInfo = null, qr = this.downloadFileImg(ops.qr)
if (ops.bg) {
bg = this.downloadFileImg(ops.bg)
// 获取图片信息
bgInfo = new Promise((resolve) => {
uni.getImageInfo({
src: ops.bg,
success(res) {
resolve(res)
},
fail() {
uni.showToast({
title: '请重试一下',
icon: 'loading'
})
}
})
})
}
return new Promise((resolve) => {
Promise.all([qr, bg, bgInfo]).then(result => {
const ctx = uni.createCanvasContext(ops.id, this)
let w = 375, h = 673, imgInfo = result[2]
ctx.setFillStyle('#fff') //设置背景色
ctx.fillRect(0, 0, w, h)
let dw = w / imgInfo.width, dh = h / imgInfo.height
// 裁剪图片中间部分
if((imgInfo.width > w && imgInfo.height > h) || (imgInfo.width < w && imgInfo.height < h)) {
if(dw > dh) {
ctx.drawImage(result[1], 0, (imgInfo.height - w / dw) / 2, imgInfo.width, w / dw, 0, 0, w, h)
} else {
ctx.drawImage(result[1], (imgInfo.height - w / dh) / 2, 0, w / dh, imgInfo.height, 0, 0, w, h)
}
} else {
if(imgInfo.width < w) {
ctx.drawImage(result[1], 0, (imgInfo.height - w / dw) / 2, imgInfo.width, w / dw, 0, 0, w, h)
} else {
ctx.drawImage(result[1], (imgInfo.width - w / dh) / 2, 0, w / dh, imgInfo.height, 0, 0, w, h)
}
}
// 绘制文本信息
ctx.setTextAlign('left')
ctx.setFillStyle('#161621')
ctx.setFontSize(w / 750 * 26)
ctx.fillText(ops.des, 20, h - 65 + j * 20)
// 绘制二维码
ctx.drawImage(result[0], w - 80, h - 80, 60, 60)
ctx.draw(false, () => {
// canvas画布转成图片并返回图片地址
uni.canvasToTempFilePath({
canvasId: ops.id,
quality: 1,
success: res => {
resolve(res.tempFilePath)
},
fail: err => {
uni.showToast({
title: '绘制失败'
})
}
}, this)
})
})
})
}
// 获取图片信息
const downloadFileImg = (url) => {
return new Promise(resolve => {
uni.getImageInfo({
src: url,
success: res => {
resolve(res.path)
},
fail: err => {
uni.showToast({
title: '网络错误请重试一下',
icon: 'loading'
})
}
})
})
}
// 保存图片到相册
const savePosterImg = (path) => {
const _this = this
uni.getSetting({
success(res) {
if(res.authSetting['scope.writePhotosAlbum'] == false) {
uni.showModal({
content: '是否授权将图片保存到相册?',
success(res) {
if(res.confirm) {
uni.openSetting({
success(res) {
setTimeout(() => {
if(res.authSetting['scope.writePhotosAlbum'] == true) {
uni.saveImageToPhotosAlbum({
filePath: path,
success: () => {
_this.toast('保存成功,快去分享到朋友圈吧~')
},
fail: () => {
_this.toast('保存失败~')
}
})
}
}, 500)
}
})
}
}
})
} else {
uni.saveImageToPhotosAlbum({
filePath: path,
success: () => {
_this.toast('保存成功,快去分享到朋友圈吧~')
},
fail: () => {
_this.toast('保存失败~')
}
})
}
}
})
}