注意事项:
分享到朋友圈仅支持分享图文、图片、文字如需要做分享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));
}
);
};