工作手记之html2canvas使用概述

什么是html2canvas?

以前我们只能通过其他的截图工具来截取图像。现代浏览器的功能已经越来越强,随着H5的逐渐普及,浏览器本身就可以截图啦。html2canvas就是这样一款前端插件,它的原理是将Dom节点在Canvas里边画出来。虽然很方便,但有以下限制:

  • 不支持iframe
  • 不支持跨域图片
  • 不能在浏览器插件中使用
  • 部分浏览器上不支持SVG图片
  • 不支持Flash
  • 不支持古代浏览器和IE,如果你想确认是否支持某个浏览器,可以用它访问http://deerface.sinaapp.com/ 试试 :)

工作原理

Html2canvas加载后将会浏览页面上的所有元素,集合所有页面元素的信息,然后用户就可以通过Html2canvas把整个页面截图下来。

换句话说,Html2canvas不会实际上的截图,而是通过从DOM读取的足够信息去建立一个页面的展示镜像。

这就会导致Html2canvas只会渲染它认识的正确的DOM元素属性,还有很多CSS属性是不会生效的,也就渲染不出来了。

使用方法

html2canvas(element, options);

带有回掉函数的:

html2canvas(element, {
    onrendered: function(canvas) {
        // canvas 是最后一个渲染的 元素
    }
});

可用参数

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

常见问题

1.图片跨域导致截图失败

报错信息如下:
Uncaught SecurityError: Failed to execute 'toDataURL' on 'HTMLCanvasElement': Tainted canvases may not be exported.

解决方法:

- 在跨域的服务器上设置header设置为允许跨域请求。
- 借助代理脚本获得外域图片的 base64 编码后的字符串

总结

虽然在使用过程中会出现一些问题,但是就目前来看,html2canvas的确为前端截图提供了非常大的作用,让我们摆脱了后台的关联处理。

你可能感兴趣的:(截图,html2canvas)