html2canvas-html圖片合成-canvas生成圖片


作用

  • html2canvas可以通過純JS對瀏覽器端經行截屏,但截圖的精確度還有待提高,部分css不可識別,所以在canvas中不能完美呈現原畫面樣式

支持的瀏覽器

  • Firefox 3.5+
  • Google Chrome
  • Opera 12+
  • IE9+
  • Safari 6+

基本語法

 //兩個參數:所需要截圖的元素id,截圖后要執行的函數, canvas為截圖后返回的最后一個canvas
 html2canvas(document.getElementById('id')).then(function(canvas) {document.body.appendChild(canvas);});

可用參數

參數名稱 類型 默認值 描述
allowTaint boolean false Whether to allow cross-origin images to taint the canvas---允許跨域
background string #fff Canvas background color, if none is specified in DOM. Set undefined for transparent---canvas的背景顏色,如果沒有設定默認透明
height number null Define the heigt of the canvas in pixels. If null, renders with full height of the window.---canvas高度設定
letterRendering boolean false Whether to render each letter seperately. Necessary if letter-spacing is used.---在設置了字間距的時候有用
logging boolean false Whether to log events in the console.---在console.log()中輸出信息
proxy string undefined Url to the proxy which is to be used for loading cross-origin images. If left empty, cross-origin images won't be loaded.---代理地址
taintTest boolean true Whether to test each image if it taints the canvas before drawing them---是否在渲染前測試圖片
timeout number 0 Timeout for loading images, in milliseconds. Setting it to 0 will result in no timeout.---圖片加載延遲,默認延遲為0,單位毫秒
width number null Define the width of the canvas in pixels. If null, renders with full width of the window.---canvas寬度
useCORS boolean false Whether to attempt to load cross-origin images as CORS served, before reverting back to proxy--這個我也不知道是干嘛的

 

 

請服搭務器環境查看

生成后:

html生成canvas canvas.toDataURL 生成base64圖片

底部4個小圖,由於跨域,2個無法生成,設置允許跨域的圖是可以生成的。

 

 

    html2canvas(document.getElementById('htmlDom'), {
        useCORS:true,//設置該屬性,圖片請求頭帶Access-Control-Allow-Origin: * 的可以生成,圖片請求如有帶301跳轉,則無法生成
        onrendered: function(canvas) {
            window.can = canvas;
            console.log(canvas);
            $("#tarPic").attr("src",canvas.toDataURL())
            document.body.appendChild(canvas);
            },
    // width: 300,
    // height: 300
    });

 示例代碼:https://files.cnblogs.com/files/zhidong123/htmlToCanvas.rar

https://github.com/zhidong10/solutions/tree/master/htmlToCanvas

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM