直接上代码
一、
npm install html2canvas -D
二、
<template>
<view>
<view style="width: 90%;margin-left: 25px;">
<view class="page" id="contractimage">
<u-form :model="form" ref="uForm">
<!-- -->
</u-form>
</view>
<view class="bottom-btn" style="margin-bottom: 20px;">
<u-row style="align-content: center;text-align: center">
<u-col span="6">
<view @click="html2canvas.emitData">下载</view>
</u-col>
</u-row>
</view>
</view>
</view>
</template>
<script>
export default {
components: {
},
data() {
return {
form: {
},
}
},
created() {
},
methods: {
showLoading() {
uni.showLoading({
title: '加载中……',
mask: true
})
},
hideLoading() {
uni.hideLoading()
},
renderFinish(opt) {
// console.log(opt.path)
console.log(opt.el)
this.img = opt.path
// 获取到图片地址(base64)
// DoSomeThing ……
this.saveBase64Img(opt.path)
},
saveBase64Img(base64) {
const bitmap = new plus.nativeObj.Bitmap('test');
bitmap.loadBase64Data(
base64,
function() {
const url = '_doc/' + new Date() + '.png'; // url建议用时间戳命名方式
console.log('url:', url);
bitmap.save(
url,
{
overwrite: true // 是否覆盖
// quality: 'quality' // 图片清晰度
},
i => {
uni.saveImageToPhotosAlbum({
filePath: url,
success: function() {
console.log('保存成功');
bitmap.clear();
}
});
},
e => {
console.log('保存失败', e);
bitmap.clear();
}
);
},
e => {
console.log('保存失败', e);
bitmap.clear();
}
);
}
}
}
</script>
<script module="html2canvas" lang="renderjs">
import html2canvas from 'html2canvas';
export default {
methods: {
emitData() {
// 根据自己需要截图区域
this.create('contractimage');
},
async create(id) {
try {
this.$ownerInstance.callMethod('showLoading', true);
const timeout = setTimeout(async () => {
const domId = document.getElementById(id);
const canvas = await html2canvas(domId, {
width: domId.offsetWidth, //设置canvas尺寸与所截图尺寸相同,防止白边
height: domId.offsetHeight, //防止白边
logging: true,
useCORS: true
});
const base64 = canvas.toDataURL('image/jpeg', 1);
this.$ownerInstance.callMethod('renderFinish', {
path: base64,
el: id
});
clearTimeout(timeout);
}, 500);
} catch (error) {
console.log(error)
}
}
}
}
</script>
<style>
</style>