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 是最后一个渲染的<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 ifletter-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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值