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

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

解决办法

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

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

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

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

使用方法:

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

带有回掉函数的:

html2canvas(element, {
    onrendered: function(canvas) {
        // canvas 是最后一个渲染的 元素
    }
});
 html2canvas($("#thecanvas"), {
    height: $("#thecanvas").outerHeight() + 20,
    onrendered: function (canvas) {
    var url = canvas.toDataURL();
    //以下代码为下载此图片功能
    var triggerDownload = $("").attr("href", url).attr("download", aData.rowNum + ".png").appendTo("body");
    triggerDownload[0].click();
    triggerDownload.remove();
    }
  });

可用参数

Name Type Default Description
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
height number null Define the heigt of the canvas in pixels. If null, renders with full height of the window.
letterRendering boolean false Whether to render each letter seperately. Necessary ifletter-spacing is used.
logging boolean false Whether to log events in the console.
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.
width number null Define the width of the canvas in pixels. If null, renders with full width of the window.
useCORS boolean false Whether to attempt to load cross-origin images as CORS served, before reverting back to proxy

你可能感兴趣的:(java)