html2canvas 将html 内容生成图片并下载

1. 下载并引入  html2canvas.js  

2. 页面 

XXX

3. js 生成并保存图片

function downPNG(pngName, pngId){

       html2canvas(document.getElementById(pngId), {

                onrendered: function(canvas) {

                var imgData = canvas.toDataURL('image/octet-stream');

                if (canvas.msToBlob) {     // IE 9+浏览器

                        var blob = canvas.msToBlob();

                        window.navigator.msSaveBlob(blob, pngName);

                 }else {

                         saveFile(imgData,pngName);

                   }

              }

        });

   }

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);

};

4. 传入页面id,点击按钮下载并保存该区域为图片

$(document).on("click",'.btn-save',function(){

downPNG( 'test.png','testId');

});

你可能感兴趣的:(html2canvas 将html 内容生成图片并下载)