html2canvas能够实现在用户浏览器端直接对整个或部分页面进行截屏。这个html2canvas脚本将当页面渲染成一个Canvas图片,通过读取DOM并将不同的样式应用到这些元素上实现。它不需要来自服务器任何渲染,整张图片都是在客户端浏览器创建。
点击查看:官方文档
点击查看:线上demo
安装引用html2canvas
npm install html2canvas
import html2canvas from 'html2canvas';
实现代码
<template>
<div id="pageDiv" :style="{'padding-top':isWeiXin || isApps?'0':'3rem'}">
<!-- 页面头部-->
<header-com :poptitle="'html2canvas截图'" :type="'doc_title'" v-if="!isWeiXin && !isApps"></header-com>
<!-- 页面的主要内容 -->
<section class="content">
<div class="qr-code-box" ref="imageToFile">
<vue-qr :logoSrc="config.logo" :text="config.value" class="qr-code-pic" :correctLevel="3" :margin="0" :dotScale="0.5"></vue-qr>
<p>哈哈哈</p>
<button type="button" class="shot-btn" @click="screenShot">截图</button>
<img id="new_img" :src="img" v-if="img"/>
</div>
</section>
</div>
</template>
<script>
import HeaderCom from "@/components/header"; //页面头部
import {changeUrl} from "@/utils/changeUrl"
import VueQr from 'vue-qr'; //二维码插件
import html2canvas from 'html2canvas'
export default {
data() {
return {
isWeiXin: TS_WEB.isWeiXin,
isApps: TS_WEB.isApp,
config: {
value: '',
logo: require('@/statics/images/system/sjbj.jpg')
},
img: ""
};
},
components: {
HeaderCom,
VueQr,
html2canvas
},
methods: {
changeUrl,
screenShot() {
html2canvas(this.$refs.imageToFile, {
width: window.innerWidth || document.documentElement.clientWidth || document.body.clientWidth,
height: window.innerHeight || document.documentElement.clientHeight || document.body.clientHeight,
}).then((canvas) => {// 第一个参数是需要生成截图的元素,第二个是自己需要配置的参数,宽高等
this.img = canvas.toDataURL('image/png');
})
}
},
mounted(){
this.config.value = "https://www.baidu.com/";
},
created() {
document.title='html2canvas截图'
}
};
</script>
<style lang="less" scoped>
// 盒子模型
#pageDiv {
width: 100%;
height: 100%;
padding-top: 0;
padding-bottom: 0;
overflow: hidden;
position: relative;
box-sizing: border-box;
.content{
height: 100%;
width: 100%;
overflow: scroll;
overflow-x: hidden;
.qr-code-box{
width: 100%;
height: 100%;
#new_img{
width: 100%;
display: block;
}
}
}
}
</style>
html2canvas可用的不同配置选项:http://html2canvas.hertzen.com/configuration/
结果: