html2canvas 的基本使用 h5将页面保存成图片 在前端生成图片

根据html2canvas官方文档的介绍,html2canvas库的工作原理并不是真正的“截图”,而是读取网页上的目标DOM节点的信息来绘制canvas,所以它并不支持所有的css属性(详情参考这里),而且期望使用的图片跟当前域名同源,不过官方也提供了一些方法来解决跨域图片的加载问题。

其使用方法很简单,引入html2canvas库以后,拿到目标dom调用一下html2canvas方法就能生成canvas对象了,由于我们的目标是生成图片,所以还需要再调用canvas.toDataURL()方法生成<img>标签的可用数据:

基本语法:

html2canvas(element, options);

html2canvas(document.body, {
  onrendered: function(canvas) {
    var url = canvas.toDataURL();//图片地址
    document.body.appendChild(canvas);
  },
  width: 300,
  height: 300
});

或者使用ES6的promise:

 html2canvas(document.querySelector('.detail-box')).then(function(canvas) {
     var url = canvas.toDataURL();//图片路径
     this.imgUrl = url;
});

可用参数

参数名称 类型 默认值 描述
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宽度
useCORS boolean false Whether to attempt to load cross-origin images as CORS served, before reverting back to proxy--这个我也不知道是干嘛的

例子:

<!DOCTYPE html>
<html>

<head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <title>html2canvas example</title>
    <script type="text/javascript" src="html2canvas.js"></script>
</head>
<script type="text/javascript">
function takeScreenshot() {
  console.log('test');
    html2canvas(document.getElementById('view'), {
        onrendered: function(canvas) {
            document.body.appendChild(canvas);
        },
      // width: 300,
      // height: 300
    });
}
</script>
<body>
    <div id="view" style="background:url(test.jpg) 50%; width: 700px; height: 500px;">
        <input type="button" value="截图" onclick="takeScreenshot()">
    </div>
</body>

</html>

参考文案:
https://www.jianshu.com/p/22bd5b98e38a
https://www.jianshu.com/p/6a07e974a7e8

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容