1. 程式人生 > >使用JS進行頁面截圖, 包括SVG的支援

使用JS進行頁面截圖, 包括SVG的支援

用到JS專案
html2canvas SVG截圖還需要用到 canvg
使用方法 引入js包
  <script src="https://code.jquery.com/jquery-3.2.1.min.js"></script>
  <script src="https://cdn.bootcss.com/html2canvas/0.4.1/html2canvas.js"></script>
注意: 需要用jq3以上版本, 1.8的各版本會報錯
增加js程式碼, 可以放到一個button的click事件裡面
       html2canvas($("#container"), { // $("#container")是你要複製生成canvas的區域,可以自己選
        onrendered: function (canvas) {
          dataURL = canvas.toDataURL("image/png");

          //下載圖片, dataURL 實際是圖片的BASE64編碼, 不是圖片的url地址, 此時圖片還沒有url

          //open_button是一個開啟圖片的按鈕
          $('#open_button').attr('href', dataURL);
        },
      })
普通網頁的截圖這樣就可以了 但是SVG圖形這樣就不行了, 截出來始終是空白, 因此需要另一個專案canvg
需要在html2canvas之前加入以下程式碼
      scrollTo(0, 0);
      var nodesToRecover = [];
      var nodesToRemove = [];
      var svgElem = $("#container").find('svg');//divReport為需要擷取成圖片的dom的id
      svgElem.each(function (index, node) {
        var parentNode = node.parentNode;
        var svg = node.outerHTML.trim();

        var canvas = document.createElement('canvas');
        canvg(canvas, svg);
        if (node.style.position) {
          canvas.style.position += node.style.position;
          canvas.style.left += node.style.left;
          canvas.style.top += node.style.top;
        }

        nodesToRecover.push({
          parent: parentNode,
          child: node
        });
        parentNode.removeChild(node);

        nodesToRemove.push({
          parent: parentNode,
          child: canvas
        });

        parentNode.appendChild(canvas);
      });
        這個會把選擇的容器內的svg物件轉化成canvas物件, 後面再接html2canvas就行了 注意: 這段程式碼會替換原始的html物件, 可以在做之前把物件先複製一份, 圖搞定之後再替回去