js实现通过canvas截图保存到本地

时间:2022-11-01 12:19:24
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title></title>
<body>
<a href="javascript:void(0);" id="downImg" onclick="downloadFile();"> 下载图片 </a>
<div class="pt18"> 
        <div class="bg-ewm">
            <span id="comName">我是公司名</span>
            <img id="ewmImg" src="" /> 
        </div> 
</div>

<script src="js/jquery.js"></script>
<script type="text/javascript" src="js/html2canvas.js"></script>
<script type="text/javascript"> //图片导出为 png 格式 var imgData =''; var type = 'png'; function downloadFile(){ html2canvas($(".pt18")).then(function(canvas) { canvas.id='mycanvas'; document.body.appendChild(canvas); var canvas = document.getElementById("mycanvas"); imgData = canvas.toDataURL(type); location = imgData; // 加工image data,替换mime type imgData = imgData.replace(_fixType(type),'image/octet-stream'); // 下载后的问题名 var filename = '二维码 .' + type; // download saveFile(imgData,filename); }); } /** * 获取mimeType * @param {String} type the old mime-type * @return the new mime-type */ var _fixType = function(type) { type = type.toLowerCase().replace(/jpg/i, 'jpeg'); var r = type.match(/png|jpeg|bmp|gif/)[0]; return 'image/' + r; }; /** * 在本地进行文件保存 * @param {String} data 要保存到本地的图片数据 * @param {String} filename 文件名 */ var saveFile = function(data, filename){ var save_link = document.createElementNS('http://www.w3.org/1999/xhtml', 'a'); save_link.href = data; save_link.download = filename; var event = document.createEvent('MouseEvents'); event.initMouseEvent('click', true, false, window, 0, 0, 0, 0, 0, false, false, false, false, 0, null); save_link.dispatchEvent(event); }; </script>
</body>
</html>