html2canvas - 實現網頁截圖(+下載截圖) 功能

實現:html2canvas + canvas.toDataURLhtml

首先,引入依賴插件:canvas

import { html2canvas } from './html2canvas';

 

html2canvas截圖模糊處理: 跨域

 1 /*圖片跨域及截圖模糊處理*/
 2 let canvasContent = document.getElementById('canvas'),//須要截圖的包裹的(原生的)DOM 對象
 3     width = canvasContent.clientWidth,//canvasContent.offsetWidth || document.body.clientWidth; //獲取dom 寬度
 4     height = canvasContent.clientHeight,//canvasContent.offsetHeight; //獲取dom 高度
 5     canvas = document.createElement("canvas"), //建立一個canvas節點
 6     scale = 4; //定義任意放大倍數 支持小數
 7 canvas.width = width * scale; //定義canvas 寬度 * 縮放
 8 canvas.height = height * scale; //定義canvas高度 *縮放
 9 canvas.style.width = canvasContent.clientWidth * scale + "px";
10 canvas.style.height = canvasContent.clientHeight * scale + "px";
11 canvas.getContext("2d").scale(scale, scale); //獲取context,設置scale

這裏倍數scale一開始是4倍,是在某個項目中太糊時搞得,可是後來到了另外一個移動端項目,在微信中截圖後的base64碼爲空。在電腦就好。詳見http://www.javashuo.com/article/p-wbfmgdqd-h.html微信

後改爲2倍就沒事了。因此應用於移動端的話,仍是改2倍比較好。dom

 

opts配置:測試

 

1 let opts = {
2     scale: scale, // 添加的scale 參數
3     canvas: canvas, //自定義 canvas
4     logging: false, //日誌開關,便於查看html2canvas的內部執行流程
5     width: width, //dom 原始寬度
6     height: height,
7     useCORS: true // 【重要】開啓跨域配置
8 };
9 //部分配置,其餘另配

 

使用:spa

 1 let shareContent = document.getElementById('XXX');
 2 export let html = (type,toDown=false) =>{
 3   html2canvas(domContent,opts).then(function(canvas){
 4     let imgUrl =  canvas.toDataURL('image/' + type);
 5     if(toDown){
 6       window.location.href = imgUrl;
 7     }else{
 8       return imgUrl;
 9     }
10   });
11 }

 

調用插件

1 html('jpg') //只獲取base64後的jpg圖片地址
2 html('png',true) //下載png格式的圖片功能

 

倉促記錄,待完善和測試日誌

 html2canvas依賴code

/*!
* html2canvas 1.0.0-alpha.12 <https://html2canvas.hertzen.com>
* Copyright (c) 2018 Niklas von Hertzen <https://hertzen.com>
* Released under MIT License
*/
相關文章
相關標籤/搜索