最近做项目为了解决把html保存一个图片,使用了html2canvas前端插件实现。
html2canvas Github地址
FileSaver Github地址
支持的浏览器
- Firefox 3.5+
- Google Chrome
- Opera 12+
- IE9+
- Safari 6+
参考demo
<html>
<head>
<meta name="layout" content="main">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<script src="https://cdn.bootcss.com/jquery/3.2.1/jquery.js"></script>
<script src="https://cdn.bootcss.com/html2canvas/0.5.0-beta4/html2canvas.js"></script>
<script src="https://cdn.bootcss.com/FileSaver.js/2014-11-29/FileSaver.js"></script>
</head>
<body>
<div style="background-color: #93ccb6;">
测试html5页面截图的生成界面如下:
</div>
<textArea id="textArea"></textArea>
<input class="example1" type="button" value="button">
</body>
<script>
$(".example1").on("click", function (event) {
event.preventDefault();
html2canvas(document.body, {
allowTaint: true,
taintTest: false,
onrendered: function (canvas) {
/**
* 保存到本地,用FileSaver这个插件
*/
canvas.toBlob(function (blob) {
saveAs(blob, "saveImage.png");
});
/**
* 生成base64图片数据
* @type {string}
*/
var dataUrl = canvas.toDataURL();
var newImg = document.createElement("img");
newImg.src = dataUrl;
document.body.appendChild(newImg);
}
});
});
</script>
</html>
可用参数
参数名称 | 类型 | 默认值 | 描述 |
---|---|---|---|
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宽度 |