本文已参与「新人创作礼」活动,一起开启掘金创作之路。
有时候我们在做分享功能的时候,有些恶心的要求要求我们把整个页面给生成一张图片
如果是H5还好 可以通过html2canvas框架来实现,但uniapp写的不是html,而是组件化的
那这个时候,我们可以用他H5+的屏幕截图的途径来实现这个功能,但是这个功能只能截取可视范围的 不能长截图 一些地图 视频 估计也有受到影响
1. 创建页面 这里就随意弄个 具体看需求去写页面
<template>
<view class="content d-flex-center flex-direction-column vh-100" id="_poster">
<image :src="test" mode="aspectFit" class="test"></image>
</view>
</template>
2. 在onReady直接截图的话 需要加定时器防止白屏 如果通过按钮方式触发调用的话 就不用
onReady() {
const that = this;
//防止切图成白屏
setTimeout(function() {
that.toImage();
}, 1000);
},
3. 通过h5+获取对应的屏幕相关信息
/* 获取屏幕信息 */
let ws = this.$mp.page.$getAppWebview();
let bitmap = new plus.nativeObj.Bitmap('test');
// 将webview内容绘制到Bitmap对象中
4. 根据屏幕内容绘制图片 生成对应的base64数据
ws.draw(
bitmap,
function(e) {
/* 获取base64 */
that.test= bitmap.toBase64Data();
},
function(e) {
console.log('截屏绘制图片失败:' + JSON.stringify(e));
},
{
check: true, // 设置为检测白屏
clip: { top: '100px', left: '0px', height: '100%', width: '100%' } // 设置截屏区域
}
5.将获取的base64数据保存到本地,获取对应的临时地址
/* 加载base64编码 */
bitmap.loadBase64Data(
bitmap.toBase64Data(),
function() {
console.log('加载Base64图片数据成功');
},
function() {
console.log('加载Base64图片数据失败:' + JSON.stringify(e));
}
);
6.将临时地址保存到相册中
/* 保存图片 */
bitmap.save(
'_doc/share.jpg',
{},
async (i)=>{
console.log('保存图片成功:' + JSON.stringify(i));
uni.saveImageToPhotosAlbum({
filePath: i.target,
success: function() {
/* 清除 */
bitmap.clear();
that.tools.toast('保存成功,请到相册中查看')
},
fail(e) {
that.tools.toast('保存失败')
}
});
},
function(e) {
console.log('保存图片失败:' + JSON.stringify(e));
}
);
这样的话 一个完整的屏幕截图就在你相册里面了
完整的代码的在下方,里面回调方法有点多 可以按照我上面的步骤分函数调用
<template>
<view class="content d-flex-center flex-direction-column vh-100" id="_poster">
<image :src="test" mode="aspectFit" class="test"></image>
</view>
</template>
<script>
export default {
data() {
return {
test: ''
};
},
onLoad() {
},
onReady() {
const that = this;
//防止切图成白屏
setTimeout(function() {
that.toImage();
}, 1000);
},
methods: {
/* 截图 */
toImage() {
const that = this;
/* 获取屏幕信息 */
let ws = this.$mp.page.$getAppWebview();
let bitmap = new plus.nativeObj.Bitmap('test');
// 将webview内容绘制到Bitmap对象中
ws.draw(
bitmap,
function(e) {
/* 获取base64 */
that.test= bitmap.toBase64Data();
/* 加载base64编码 */
bitmap.loadBase64Data(
bitmap.toBase64Data(),
function() {
console.log('加载Base64图片数据成功');
/* 保存图片 */
bitmap.save(
'_doc/share.jpg',
{},
async (i)=>{
console.log('保存图片成功:' + JSON.stringify(i));
uni.saveImageToPhotosAlbum({
filePath: i.target,
success: function() {
/* 清除 */
bitmap.clear();
that.tools.toast('保存成功,请到相册中查看')
},
fail(e) {
that.tools.toast('保存失败')
}
});
},
function(e) {
console.log('保存图片失败:' + JSON.stringify(e));
}
);
},
function() {
console.log('加载Base64图片数据失败:' + JSON.stringify(e));
}
);
},
function(e) {
console.log('截屏绘制图片失败:' + JSON.stringify(e));
},
{
check: true, // 设置为检测白屏
clip: { top: '100px', left: '0px', height: '100%', width: '100%' } // 设置截屏区域
}
);
},
};
</script>