用html2canvas.js 将前端HTML页面生成图片
首先去html2canvas官网下载html2canvas.js文件
html2canvas官网地址:http://html2canvas.hertzen.com/
HTML
<div id="host_file" class="container"> <div id="view" class="print_wrap"> <div class="host_file_top_title_box"> <p>123</p> <p>456</p> </div> <div id="moveDiv" onclick="renderPdf">下载页面</div> </div> </div>
js
function renderPdf() {
var dom=document.getElementsByClassName("container")[0];
var domWrap =document.getElementsByClassName("print_wrap")[0];
var width = dom.offsetWidth; //获取dom 宽度
var height = dom.offsetHeight; //获取dom 高度
var offsetTop = dom.offsetTop;
var scaleBy =1;
var canvas =document.createElement('canvas');
canvas.width = width * scaleBy; //定义canvas 宽度 * 缩放
canvas.height = (height + offsetTop) * scaleBy; //定义canvas(高度 +偏移量 )*缩放
canvas.style.width =width * scaleBy + 'px';
canvas.style.height =(height + offsetTop) * scaleBy + 'px';
var context =canvas.getContext('2d');
context.scale(scaleBy, scaleBy);
var filename =(new Date()).getTime() + '.' + "png";
html2canvas(dom, {
background:"#ffffff",
canvas: canvas,
useCORS: true,
scale: 1,
width: width,
height: height
}).then(function(canvas){
var type ='png';
var imgData =canvas.toDataURL(type);
var _fixType =function(type) {
type =type.toLowerCase().replace(/jpg/i, 'jpeg');
var r =type.match(/png|jpeg|bmp|gif/)[0];
return 'images/' + r;
};
imgData =imgData.replace(_fixType(type),'image/octet-stream');
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);
};
saveFile(imgData,filename);
})
}