该脚本允许您直接在用户的浏览器上对网页或其部分内容进行“截屏”。截图是基于DOM的,因此可能不是100%准确的真实表示,因为它没有真正的截图,但基于页面上可用的信息构建截图。
该脚本通过读取DOM和应用于元素的不同样式,将当前页面呈现为画布图像
1.安装
npm install html2canvas
2.在Test.vue组件中使用
<template>
<div id="container">
<div class="img-container" v-if="imgBlobData">
<img :src="imgBlobData" alt="" />
</div>
<button @click="convertToImage">
点我
<img src="../assets/logo.png" alt="" />
</button>
</div>
</template>
<script>
import html2canvas from "html2canvas";
export default {
data() {
return {
imgBlobData: undefined,
};
},
methods: {
convertToImage(container, options = {}) {
container = document.querySelector("#container");
// 设置放大倍数
const scale = window.devicePixelRatio;
// console.log(scale);//
// 传入节点原始宽高
const _width = container.offsetWidth;
const _height = container.offsetHeight;
// console.log(_width, _height);
let { width, height } = options;
width = width || _width;
height = height || _height;
// console.log(width, height);
// html2canvas配置项
const ops = {
scale,
useCORS: true,//表示允许跨域资源共享,注意不能与 allowTaint 同时配置为 true
allowTaint: false,//canvas 的 CanvasRenderingContext2D 属于浏览器的对象,如果渲染过跨域资源,浏览器就认定 canvas 已经被污染了 Taint:污点
...options,
};
return html2canvas(container, ops).then((canvas) => {
// 返回图片的二进制数据
// console.log(canvas.toDataURL("image/png"));
this.imgBlobData = canvas.toDataURL("image/png");
console.log(this.imgBlobData);
});
},
},
};
</script>
切图效果如下所示:
切图效果.png
其实是将我原来的图片放大了对应的倍数以后的图片.








网友评论