html2canvas将页面dom元素内容渲染成图片保存至本地
html2canvas:https://html2canvas.hertzen.com/configuration/
github:https://github.com/niklasvh/html2canvas
效果
代码
<!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="./js/html2canvas.js"></script>
</head><body><div id="root"><h3>名片</h3><div class="person"><img src="./assets/header.png" alt=""></div></div><button id="downloadImg">点击</button>
</body><script>let dom = document.getElementById("downloadImg");dom.onclick = function () {// 实现保存为图片的第一步:html转为canvashtml2canvas(document.getElementById("root"), {scale: window.devicePixelRatio,height: 800,width: 800,backgroundColor: null//设置背景透明}).then(function (canvas) {let link = document.createElement('a');// 实现保存图片的目标只需要将canvas转image即可。// canvas的toDataURL方法将canvas输出为data: URI类型的图片地址,再将该图片地址赋值给元素的src属性即可。link.href = canvas.toDataURL();// 保存图片link.setAttribute('download', '图片canvas.png');link.style.display = 'none';document.body.appendChild(link);link.click();document.removeChild(link)});}
</script></html>
当图片来源于服务器,需要设置跨域
<body><div id="root"><h3>名片</h3><div class="person"><img style="width: 600px; height: 400px;" src="https://img0.baidu.com/it/u=3976250177,3245140550&fm=253&fmt=auto&app=120&f=JPEG?w=1200&h=675" alt=""></div></div><button id="downloadImg">点击</button>
</body><script>let dom = document.getElementById("downloadImg");dom.onclick = function () {// 实现保存为图片的第一步:html转为canvashtml2canvas(document.getElementById("root"), {useCORS: true,//图片设置跨域scale: window.devicePixelRatio,height: 800,width: 800,// backgroundColor: null}).then(function (canvas) {let link = document.createElement('a');// 实现保存图片的目标只需要将canvas转image即可。// canvas的toDataURL方法将canvas输出为data: URI类型的图片地址,再将该图片地址赋值给元素的src属性即可。link.href = canvas.toDataURL();// 保存图片link.setAttribute('download', '图片canvas.png');link.style.display = 'none';document.body.appendChild(link);link.click();document.removeChild(link)});}
</script>