<!--div轉成圖片並下載--> <script src="./js/html2canvas.min.js"></script> <script> // edited from https://developer.mozilla.org/en-US/docs/Web/API/HTMLCanvasElement/toBlob#Polyfill var dataURIToBlob = function (imgName, dataURI, callback) { var binStr = atob(dataURI.split(',')[1]), len = binStr.length, arr = new Uint8Array(len); for (var i = 0; i < len; i++) { arr[i] = binStr.charCodeAt(i); } callback(imgName, new Blob([arr])); } var callback = function (imgName, blob) { var triggerDownload = $("<a>").attr("href", URL.createObjectURL(blob)).attr("download", imgName).appendTo("body").on("click", function () { if (navigator.msSaveBlob) { return navigator.msSaveBlob(blob, imgName); } }); triggerDownload[0].click(); triggerDownload.remove(); }; function createImg() { var getPixelRatio = function (context) { // 獲取設備的PixelRatio var backingStore = context.backingStorePixelRatio || context.webkitBackingStorePixelRatio || context.mozBackingStorePixelRatio || context.msBackingStorePixelRatio || context.oBackingStorePixelRatio || context.backingStorePixelRatio || 0.5; return (window.devicePixelRatio || 0.5) / backingStore; }; //生成的圖片名稱 var imgName = "cs.png"; var shareContent = document.getElementsByTagName("body")[0]; let scale = 3; var opts = { //scale: scale, /*canvas: canvas, width: width, height: height,*/ dpi: window.devicePixelRatio, useCORS: true, // 【重要】開啟跨域配置 //width: window.screen.availWidth, //顯示的canvas窗口的寬度 //height: window.screen.availHeight, //顯示的canvas窗口的高度 width: window.document.body.offsetWidth, //獲取當前網頁的寬度 height: window.document.body.offsetHeight, //獲取當前網頁的高度 windowWidth: document.body.scrollWidth, //獲取X方向滾動條內容 windowHeight: document.body.scrollHeight, //獲取Y方向滾動條內容 x: 0, //頁面在水平方向沒有滾動,故設置為0 y: window.pageYOffset //頁面在垂直方向的滾動距離 }; html2canvas(shareContent, opts).then(function (canvas) { const context = canvas.getContext("2d"); // 【重要】關閉抗鋸齒 https://segmentfault.com/a/1190000011478657 context.imageSmoothingEnabled = false; context.webkitImageSmoothingEnabled = false; context.msImageSmoothingEnabled = false; context.imageSmoothingEnabled = false; let imgUrl = canvas.toDataURL("image/png").replace("image/png","image/octet-stream"); //console.log("imgUrl",imgUrl); dataURIToBlob(imgName, imgUrl, callback); }); } </script>