uni-app app分享到微信聊天作为小程序,且截图页面作为小程序分享封面保姆级教程(app分享到微信模仿微信小程序分享封面绘制)

本文介绍了如何使用Vue3和HBuilderX开发微信小程序时,实现自定义分享功能,包括封装截图压缩方法以确保封面图质量,以及创建canvas绘制分享海报的过程。
摘要由CSDN通过智能技术生成

注意事项:

分享到朋友圈仅支持分享图文、图片、文字如需要做分享app到朋友圈一般是canvas绘制成海报分享图片。
本项目是基于vue3 hbuilder x3.99实现
代码复制进去就可用,有问题可留言或私信

步骤

1. 封装截图压缩的方法

js部分,在utils.js中封装一个压缩图片的方法,因为分享微信小程序的封面图不能超过120kb(大概),否则会导致微信进行压缩从而超级模糊

export function imageCompress(file){
    return new Promise((resolve, reject)=>{
        let { size,path, tempFilePath } = file
        let type  = path.split(".")[1]
        //大于120kb进行压缩
        if(size <= 120*1024){
            resolve(file)
            return false
        } 
        uni.compressImage({
            src: tempFilePath,
            quality: 70,
            width:'80%',
            height: 'auto',
            success: res => {
                let newPath = res.tempFilePath+type
                uni.getFileInfo({
                    filePath:res.tempFilePath,
                    success:async (info)=>{
                        console.log('compress img:', info.size / 1024);
                        let newFile = {...file,size:info.size,path:newPath,tempFilePath:res.tempFilePath}
                        resolve(await imageCompress(newFile))
                    }
                })
            },
            fail:err=>{
                console.log('compressImage fail:', err)
            }
        })    
    })
}

2. 创建canvas,设置透明度为0,固定定位在页面上,截图绘制 分享

因为分享小程序封面是5:4比例,因此设置成750rpx:600rpx。

<button @click="onShare('微信')">分享到微信</button>
<button @click="onShare('朋友圈')">分享到朋友圈</button>
<canvas style="width: 750rpx; height: 600rpx; position: fixed; top: 0; left: 0; z-index: 1; pointer-events: none; opacity: 0" canvas-id="myNavCanvas"></canvas>
import { imageCompress } from "@/utils/utils.js";
const shareTitle = "分享标题";
const pageUrl = "pages/index/index";
const posterUrl = ref("");
//点击分享按钮
const onShare = (type) => {
	// #ifdef APP-PLUS
    if (type == "微信") {
        let url = pageUrl + "?id=1"; //可携带参数
        uni.showLoading({
            title: "加载中",
            mask: true,
        });
        shareScreenshot(url, "WXSceneSession", shareTitle);
    } else if (type == "朋友圈") {
        if (posterUrl.value) {
            uni.share({
                provider: "weixin",
                scene: "WXSceneTimeline",
                type: 2,
                imageUrl: posterUrl.value,
                success: (ret) => {
                    console.log(JSON.stringify(ret));
                },
            });
        } else {
            let url = pageUrl + "?id=1";
            uni.showLoading({
                title: "加载中",
                mask: true,
            });
            shareScreenshot(url, "WXSceneSession", shareTitle);
        }
    }
    // #endif
}
//绘制分享封面图
const shareScreenshot = (url, scene, title) => {
    const pages = getCurrentPages();
    const page = pages[pages.length - 1];
    const currentWebview = page.$getAppWebview();
    const bitmap = new plus.nativeObj.Bitmap("amway_img");
    //获取当前页面实例截图
    currentWebview.draw(
        bitmap,
        () => {
            let imgName = "_downloads/sharePic" + Date.now() + ".png"; //设置不同的图片名称,方便分享完成后删除系统中存储的临时图片  节省app缓存
            bitmap.save(imgName, {}, (i) => {
                let ctx = uni.createCanvasContext("myNavCanvas"); //获取canvas实例
                let h = (uni.getSystemInfoSync().windowWidth * 4) / 5; //获取系统宽度下5:4的高度  作为canvas绘制的高度
                // drawImage(sx, sy, sWidth, sHeight, dx, dy, dWidth, dHeight)
                uni.getImageInfo({
                    src: i.target,
                    success: (image) => {
                    	//120是我自定义顶部navbar的高度  120rpx ,因此用uni.upx2px转成px用于计算
                    	//截图的时候会把顶部自定义navbar截图进去,因此需要获得高度,裁剪掉顶部navbar部分,剩下的用于绘制封面
                        let m = ((uni.getSystemInfoSync().statusBarHeight + uni.upx2px(120)) * image.width) / uni.getSystemInfoSync().windowWidth; 
                        //drawImage的具体参数看下图
                        ctx.drawImage(i.target, 0, m, image.width, (image.width * 4) / 5, 0, 0, uni.getSystemInfoSync().windowWidth, h);
                        ctx.draw(false, () => {
                        	//canvas转临时图片地址
                            uni.canvasToTempFilePath({
                                canvasId: "myNavCanvas",
                                fileType: "jpg", //绘制成jpg方便压缩
                                success: (res) => {
                                	posterUrl.value = res.tempFilePath;
                                    uni.getFileInfo({
                                        filePath: res.tempFilePath,
                                        success: (info) => {
                                            let newFile = { size: info.size, path: res.tempFilePath, tempFilePath: res.tempFilePath };
                                            //压缩图片
                                            imageCompress(newFile).then((file) => {
                                                uni.hideLoading(); //loading不会被截图因此在压缩完成后再取消
                                                uni.share({
                                                    provider: "weixin",
                                                    scene,
                                                    type: 5,
                                                    imageUrl: file.tempFilePath,
                                                    title,
                                                    miniProgram: {
                                                        id: "gh_d4fxxxxxxxx", //你小程序的原始id
                                                        path: url,
                                                        type: 0, //正式版
                                                        webUrl: store.state.webUrl, //兼容低版本的网页链接,必填不然分享不成功,随便填一个也行
                                                    },
                                                    success: (ret) => {
                                                        uni.showToast({
                                                            title: "分享成功",
                                                            icon: "none",
                                                        });
                                                        // 图片保存成功后,将临时保存的图片删除
                                                        plus.io.resolveLocalFileSystemURL(
                                                            imgName,
                                                            function (entry) {
                                                                entry.getMetadata(function (metadata) {
                                                                    // console.log("fileCount=" + metadata.fileCount);
                                                                    entry.remove(); //删除单个文件
                                                                });
                                                            },
                                                            function (error) {
                                                                // uni.showToast({ title: "下载文件" });
                                                                console.log("error" + error);
                                                            }
                                                        );
                                                        bitmap.clear();
                                                    },
                                                    fail: (err) => console.log("share err:", err),
                                                });
                                            });
                                        },
                                    });
                                },
                                fail: (err) => console.log("canvasToTempFilePath err:", err),
                            });
                        });
                    },
                });
            });
        },
        (e) => {
            console.log("保存图片失败:" + JSON.stringify(e));
        },
        (e) => {
            console.log("截屏绘制图片失败:" + JSON.stringify(e));
        }
    );
};

drawImage详解

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

天外来鹿

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值