功能:
1.兼容 PC 和 Mobile;
2.对指定的区域进行截取;
3.可以控制截图大小;
4.截图生成base64图片地址
一、安装插件
npm install html2canvas --save 或 yarn add html2canvas
二、在.vue页面引入使用
import html2canvas from "html2canvas";
三、以下代码可直接复制
<template>
<div id="page">
<div>页面截图 只截取指定区域</div>
<!-- 截图区域 -->
<div class="content" ref="content">
<div style="float:left">这里是丰富的网页内容...</div>
<input type="text" style="width:300px;height: 30px;">
<div style="height:100px">div盒子</div>
<div style="height:100px">300px</div>
</div>
<button class="btn" @click="getPrintScreen">获取截图</button>
<div class="img-box">
<h2>截图结果:</h2>
<!-- 通过img标签把获取到的截图呈现出来 -->
<img :src="imgUrl" alt="" />
</div>
</div>
</template>
<script>
import html2canvas from "html2canvas"
export default {
name: "Screenshot",
data () {
return {
imgUrl: null, //截图地址
}
},
methods: {
//获取截图方法
getPrintScreen () {
// 第一个参数是需要生成截图的元素,第二个是自己需要配置的参数,宽高等
html2canvas(this.$refs.content, {
// width: 30, //截图宽度
// height: 50, //截图高度
backgroundColor: null, //画出来的图片有白色的边框,不要可设置背景为透明色(null)
useCORS: true, //支持图片跨域
scale: 1, //设置放大的倍数
}).then((canvas) => {
// 把生成的base64位图片上传到服务器,生成在线图片地址
let url = canvas.toDataURL("image/png") // toDataURL: 图片格式转成 base64
console.log('base64图片地址', url)
this.imgUrl = url
})
},
},
};
</script>
<!-- 本demo样式代码(不重要) -->
<style lang="less">
#page {
padding: 0;
width: 100%;
height: 100%;
background-color: #fff;
.content {
text-align: center;
background-color: rgb(243, 161, 152);
}
.btn {
display: block;
width: 60vw;
height: 50px;
background: #79c76f;
border-radius: 2vw;
border: none;
font-family: Source Han Sans CN;
font-weight: 400;
color: #ffffff;
letter-spacing: 4px;
text-align: center;
margin: 30px 0 20px 40px;
}
}
</style>