If it can be achieved, remember to like and share, thank you~
I saw some Google plug-ins that can take partial screenshots of web pages or screenshots of the entire web page, so I thought about making a demo about front-end screenshots. Finally selected html2canvas
1. Download the installation package
Install NPM
npm install --save html2canvas
Someone
Install Yarn
yarn add html2canvas
2. Look at the renderings first
- Click the [Partial Screenshot] button to customize the desired location
- Click the [Screenshot the entire webpage] button to take a screenshot of the entire webpage.
3. Code demonstration
vue statement
<script setup lang="ts">
import {
onMounted,toRef } from "vue";
import html2canvas from "html2canvas";
let imgUrl: any = toRef('')
// 生成快照
const convertToImage = (container, options?: any) => {
// 设置放大倍数
const scale = window.devicePixelRatio;
// 传入节点原始宽高
const _width = container.offsetWidth;
const _height = container.offsetHeight;
if(options){
let {
width, height } = options;
width = width || _width;
height = height || _height;
}
// html2canvas配置项
const ops = {
scale,
// width,
// height,
useCORS: true,
allowTaint: false,
...options
};
return new Promise((resolve) => {
html2canvas(container, ops).then(canvas => {
// document.body.appendChild(canvas); // 直接是一个canvas图片
// 返回图片的二进制数据
// return canvas.toDataURL("image/png");
// let dataURI = canvas.toDataURL('image/' + format, quality); ps: 弃用
// 生成的Base64图片将比使用toDataURL方法生成的小得多,并且可以方便地在浏览器中显示和处理。
canvas.toBlob((blob: any) => {
const reader = new FileReader();
reader.readAsDataURL(blob);
reader.onloadend = () => {
resolve(reader.result);
}
}, 'image/jpeg');
});
});
}
const clickBtn = async (num) => {
let imgBlobData: any = ''
// 调用函数,取到截图的二进制数据,对图片进行处理(保存本地、展示等)
if(num === 1){
// 局部
imgBlobData = await convertToImage(document.getElementById('content'));
}else if(num === 2){
// 整个网页
imgBlobData = await convertToImage(document.body);
}
imgUrl.value = imgBlobData
}
</script>
<template>
<div class="contrainer">
<div>
<h1>要呈现的HTML内容:</h1>
<div id="content">将此元素中的内容仅渲染到现有的画布元素上</div>
</div>
<div>
<h1>现有画布:</h1>
<div class="img">
<a-image :src="imgUrl"></a-image>
</div>
</div>
<div class="btnCon">
<a-button
class="btn"
size="large"
@click="clickBtn(1)"
>局部截图</a-button
>
<a-button
class="btn"
size="large"
@click="clickBtn(2)"
>整个网页截图</a-button
>
</div>
</div>
</template>
<style>
.contrainer{
display: flex;
flex-direction: column;
}
.img {
width: 500px;
height: 300px;
border: 1px solid black;
}
.btnCon{
display: flex;
}
.btn {
cursor: pointer;
width: 200px;
margin: 20px 20px;
}
#content {
background: rgba(100, 255, 255, 0.5);
padding: 50px 10px;
}
</style>
The point is
html2canvas(document.querySelector("#capture")).then(canvas => {
document.body.appendChild(canvas)
});