Live2D

html2canvas--页面dom转图片

最近工作上遇到需求,要实现分享页面功能。(具体就是把我们页面的dom转化为一张图保存,然后通过图片进行分享)

公司内部有相对应的spt(html-to-image)外部就不适用了。

自己也调研了一下发现常见的可引用 html2canvas.js来实现。仔细看了官网(http://html2canvas.hertzen.com),总结一下自己的用法:

 

 
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
<script src="./html2canvas.js"></script>
<style>
.box {
width: 500px;
height: 500px;
color: red;
background-color: black;
}
</style>
</head>
<body>
<div class="box">
<div>佳文</div>
<img src="https://img.alicdn.com/imgextra/i3/O1CN014iA0NU1m4hpCi1B9t_!!6000000004901-2-tps-173-209.png" alt="" srcset="">
</div>
<button id="button">dom转图片</button>
</body>
<script>
const btn = document.getElementById("button");
const ratio = ((document.documentElement.clientHeight || document.body.clientHeight) / (document.documentElement.clientWidth || document.body.clientWidth)) / (1624 / 750);


btn.onclick = function () {
document.body.scrollTop = document.documentElement.scrollTop = 0;
const node = window.document.querySelector('.box');
if (!node) {
return;
}
let imgHeight = node.offsetHeight;
let imgWidth = node.offsetWidth;
let scale = window.devicePixelRatio;

html2canvas(node, {
useCORS: true,
scale: scale,
width: 500,
height: 500,
backgroundColor: 'rgba(0, 0, 0, 0)',
allowTaint: true,
removeContainer: true,
}).then((canvas) => {
// const newCanvas = scaleCanvas(canvas, imgWidth * ratio, imgHeight * ratio);

const image = canvas.toDataURL('image/png');
console.log(image)
})
};

</script>
</html>
posted @ 2021-09-28 16:07  喻佳文  阅读(244)  评论(0编辑  收藏  举报