html2canvas將Html5轉換為圖片並下載到本地,純JS實現
阿新 • • 發佈:2018-11-22
首先引入html2canvas.js
<script type="text/javascript" src="http://html2canvas.hertzen.com/dist/html2canvas.js"></script>
然後是檔案本地儲存並重命名的一段函式,最後事件函式處理就可以了
/** * 在本地進行檔案儲存 * @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); };
function exportToPic() { html2canvas( document.body, { onrendered: function (canvas) { var pageData = canvas.toDataURL('image/jpeg', 1.0); console.log(pageData) //window.location=(pageData.replace("image/jpeg", "image/octet-stream")); saveFile(pageData.replace("image/jpeg", "image/octet-stream"),new Date().getTime()+".jpeg"); }) }