html部分
<!-- 分享海报 -->
<u-popup
:show="showShareImg"
:safeAreaInsetBottom="false"
:customStyle="{
height: '960rpx',
}"
round="24rpx"
mode="center"
@close="showShareImg = false"
>
<u--image :src="shareImg" radius="24rpx" width="600rpx" height="960rpx"></u--image>
</u-popup>
<canvas class="canvas" canvas-id="myCanvas" id="myCanvas"></canvas>
js部分
// 处理canvas转图片分享
async handelCanvas() {
// 这一步是获取小程序码图片,小程序码图片需要由后端生成
const params = {
bizId: this.id,
sceneId: 0,
belongUserId: this.$store.state.userInfo?.id || '',
};
const {
data: qrCodeImg } = await ShopApi.getQrCodeImg(params);
// 画canvas
$loading.show('正在生成图片', false);
const {
skuPic, skuName, specifications } = this.currentProd;
const ctx = uni.createCanvasContext('myCanvas', this);
// 白色背景
ctx.beginPath();
ctx.setFillStyle('#fff');
ctx.fillRect(0, 0, 300, 480);
// 其他canvasn内容。。。
// 在canvas画小程序码图片
// 引入公共方法utils文件里的获取图片信息的方法,在线图片要通过这个方法转成临时路径的图
export const getImageInfo = async (imgSrc) => new Promise((resolve, reject) => {
uni.getImageInfo({
src: imgSrc,
success: (image) => {
resolve(image);
},
fail: (err) => {
toast('获取图片信息失败')
reject(err);
}
});
});
const qrCodeImgInfo = await getImageInfo(qrCodeImg);
ctx.drawImage(qrCodeImgInfo.path, 185, 355.5, 100, 100);
// 执行绘图
ctx.draw(true, () => {
// canvas转图片, [canvasToTempFilePath参考文档](https://uniapp.dcloud.net.cn/api/canvas/canvasToTempFilePath.html#canvastotempfilepath)
uni.canvasToTempFilePath(
{
canvasId: 'myCanvas',
width: 300,
height: 480,
// 生成的图片尺寸,2倍图清楚
destWidth: 300 * 2,
destHeight: 480 * 2,
quality: 1,
fileType: 'jpg',
success: res => {
// 获取图片路径
this.shareImg = res.tempFilePath; // 赋值给图片
this.showShareImg = true; // 弹窗显示
},
fail: err => {
toast('图片生成失败');
},
complete: () => {
$loading.close();
},
},
this
);
});
},
注意点
uni.getImageInfo转换在线图片的时候需要在微信公众平台配置对应的downloadFile合法域名,也就是图片的合法域名
生成海报如下示例图:
生成分享海报之后如何扫码传参跳转到对应页面
文档说明:https://developers.weixin.qq.com/miniprogram/dev/OpenApiDoc/qrcode-link/qr-code/getUnlimitedQRCode.html
获取 scene 值
scene 字段的值会作为 query 参数传递给小程序/小游戏。用户扫描该码进入小程序/小游戏后,开发者可以获取到二维码中的 scene 值,再做处理逻辑。
调试阶段可以使用开发工具的条件编译自定义参数 scene=xxxx 进行模拟,开发工具模拟时的 scene 的参数值需要进行 encodeURIComponent
小程序
Page({
onLoad (query) {
// scene 需要使用 decodeURIComponent 才能获取到生成二维码时传入的 scene
const scene = decodeURIComponent(query.scene)
}
})
示例代码
onLoad(options) {
const {
id, scene } = options;
// 扫码跳转的scene 需要使用 decodeURIComponent 才能获取到生成二维码时传入的 scene
if (scene) {
this.scene = decodeURIComponent(scene);
this.getQrCodeData(); // 获取二维码数据
} else {
this.id = id;
this.getById();
}
},
methods: {
async getQrCodeData() {
// 调用后端接口获取二维码数据拿到商品id
const params = {
id: this.scene,
}
const {
data: {
bizId },
} = await ShopApi.getQrCodeData(params);
// 获取商品详情
this.id = bizId;
this.getById();
},