有時候我們在做分享功能的時候,有些噁心的要求要求我們把整個頁面給生成一張圖片
如果是H5還好 可以通過html2canvas框架來實現,但uniapp寫的不是html,而是組件化的
那這個時候,我們可以用他H5+的屏幕截圖的途徑來實現這個功能
<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>