- 首先需要引入 html2canvas 库:
<script src="https://html2canvas.hertzen.com/dist/html2canvas.min.js"></script>
- 在需要将 DOM 转换为 canvas 的地方,获取 DOM 对象并调用 html2canvas 函数:
const element = document.getElementById('my-element');
html2canvas(element).then(canvas => {
document.body.appendChild(canvas);
});
- 可以传递一些选项来配置转换过程,例如:
const options = {
scale: 2 // 将 canvas 放大 2 倍
}
html2canvas(element, options).then(canvas => {
document.body.appendChild(canvas);
});
- html2canvas 还可以处理整个页面,只需传递 document.body 作为参数即可:
html2canvas(document.body).then(canvas => {
document.body.appendChild(canvas);
});