您的位置:首页 > Web前端 > HTML

html2canvas截取界面html并保存到本地

2016-05-16 09:58 423 查看
最近的项目有一个需求,就是以一张图片为背景图,图片上的各个空格显示成前台获取到的数据,后台点击生成图片按钮后, 生成一张新的图片保存到本地;

解决办法

最后选择了js截取html生成图片保存到本地的办法,因为后台生成的效果简单的还好,复杂的效果并不理想;

插件描述:html2canvas是通过对DOM元素的信息提取渲染页面;

工作原理:html2canvas不会实际上的截图,而是通过从DOM读取的足够信息去建立一个页面的展示镜像。这会导致html2canvas只会渲染它认识的正确的DOM元素属性,很多css属性是不会生效的,也就渲染不出来;

限制:所有的图片都需要在当前域下,这样html2canvas才能不通过代理去读取到。同样的,如果你的页面上有其他的被跨越内容渲染的canvas元素,html2canvas将不能准确渲染下来;也就是说 如果你的图片在页面是隐藏的,那么生成图片的时候是不会有的。

使用方法:

html2canvas(element, options);
element是需要生成图片的区域的最外围div的id


带有回掉函数的:

html2canvas(element, {
onrendered: function(canvas) {
// canvas 是最后一个渲染的<canvas> 元素
}
});
html2canvas($("#thecanvas"), {
height: $("#thecanvas").outerHeight() + 20,
onrendered: function (canvas) {
var url = canvas.toDataURL();
//以下代码为下载此图片功能
var triggerDownload = $("<a>").attr("href", url).attr("download", aData.rowNum + ".png").appendTo("body");
triggerDownload[0].click();
triggerDownload.remove();
}
});
可用参数
NameTypeDefaultDescription
allowTaintbooleanfalseWhether to allow cross-origin images to taint the canvas
backgroundstring#fffCanvas background color, if none is specified in DOM. Set undefined for transparent
heightnumbernullDefine the heigt of the canvas in pixels. If null, renders with full height of the window.
letterRenderingbooleanfalseWhether to render each letter seperately. Necessary if[code]letter-spacing is
used.
loggingbooleanfalseWhether
to log events in the console.
proxystringundefinedUrl
to the proxy which is to be used for loading cross-origin images. If left empty, cross-origin images won't be loaded.
taintTestbooleantrueWhether
to test each image if it taints the canvas before drawing them
timeoutnumber0Timeout
for loading images, in milliseconds. Setting it to 0 will result in no timeout.
widthnumbernullDefine
the width of the canvas in pixels. If null, renders with full width of the window.
useCORSbooleanfalseWhether
to attempt to load cross-origin images as CORS served, before reverting back to proxy
[/code]
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: