dom-to-image 示例代码 兼容移动端操作
<!DOCTYPE html> <html> <head> <title>Save Webpage as Image</title> <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no" /> <script src="https://cdnjs.cloudflare.com/ajax/libs/dom-to-image/2.6.0/dom-to-image.min.js"></script> </head> <body> <div id="myElement"> 1, World!</h1> <p>This is a sample paragraph.</p> <!-- <img src="image2.png" alt="Sample Image"> --> </div> <button onclick="saveAsImage()">Save as Image</button> <script src="/static/admin/vendor/js/jquery.js"></script> <script> function saveAsImage() { // 获取要保存为图片的HTML元素 var element = document.getElementById("myElement"); // 使用dom-to-image库将HTML元素转换为图片 domtoimage.toPng(element) .then(function(dataUrl) { // 创建一个a元素,用于下载图片 var link = document.createElement("a"); link.download = "666.png"; link.href = dataUrl; // 将a元素添加到文档中,并模拟点击下载链接 document.body.appendChild(link); link.click(); document.body.removeChild(link); }) .catch(function(error) { console.error('oops, something went wrong!', error); }); } // 在移动设备上,需要将按钮的click事件替换为touchend事件 if ('ontouchstart' in window) { var button = document.querySelector('button'); button.addEventListener('touchend', saveAsImage); button.addEventListener('click', function(event) { event.preventDefault(); }); } </script> </body> </html>