页面部分:
html
<template>
<div ref="homePage" class="home-container rel">
<div class="snap-box abs">
<div title="页面快照" class="z-pointer" @click="newSnapShot()">
<img :src="snapCamera" alt="快照生成">
</div>
</div>
<el-image-viewer
v-if="imgUrl"
:on-close="()=>{imgUrl=''}"
:url-list="[imgUrl]" />
</div>
</template>
js代码部分:
javascript
/**
* 图片blob转图片base64
* @param blob
*/
export const blobToBase64 = (blob) => {
return new Promise((resolve, reject) => {
const fileReader = new FileReader();
fileReader.onload = (e) => {
resolve(e.target.result);
};
// readAsDataURL
fileReader.readAsDataURL(blob);
fileReader.onerror = () => {
reject(new Error('blobToBase64 error'));
};
});
}
import html2canvas from 'html2canvas';
import { blobToBase64 } from '@/utils/helper.js';
export default {
name: 'Home',
components: {
'el-image-viewer': () => import('element-ui/packages/image/src/image-viewer'),
},
data() {
return {
tooltipRemark,
loading: false,
imgUrl: '',
};
},
methods: {
// 生成快照
newSnapShot() {
this.loading = true;
const { ClipboardItem } = window;
html2canvas(this.$refs.homePage).then((canvas) => {
// 将canvas转为blob对象
canvas.toBlob(async (blob) => {
if (typeof (navigator.clipboard) === 'undefined' && !ClipboardItem) {
await blobToBase64(blob).then((res) => {
this.imgUrl = res;
this.$message({
message: '快照生成成功',
type: 'success',
duration: 2000,
});
}).catch(() => {
this.$message({
message: '快照生成失败',
type: 'warning',
duration: 2000,
});
}).finally(() => {
this.loading = false;
});
return;
}
// 将blob对象放入剪切板item中
// eslint-disable-next-line no-undef
const data = [new ClipboardItem({ [blob.type]: blob })];
// 写入剪切板,成功会执行resolve,失败则走reject
await navigator.clipboard.write(data).then(() => {
this.$message({
message: '已保存到粘贴板',
type: 'success',
duration: 2000,
});
this.loading = false;
}, () => {
this.$message({
message: '保存截图失败',
type: 'warning',
duration: 2000,
});
this.loading = false;
});
}, 'image/png');
}).catch(() => {
this.loading = false;
});
},
},
};