使用 html2canvas 将页面保存成图片

有时我们需要实现在浏览器端直接对整个或部分页面进行截屏,比如移动端常见的“长按网页保存为图片”功能。这个借助 html2canvas 这个第三方 js 库即可实现,下面通过样例演示其如何使用。

一、基本介绍

1,什么是 html2canvas
html2canvas 可以通过获取 HTML 的某个元素,然后生成 Canvas,从而让用户保存为图片。
html2canvas 工作原理是将当页面渲染成一个 Canvas 图片,通过读取 DOM 并将不同的样式应用到这些元素上。
html2canvas 不需要来自服务器任何渲染,整张图片都是在客户端浏览器创建。
2,注意事项

当然并不是所有的页面元素都可以进行转换的,下面是不支持的情况:
不支持 iframe
不支持跨域图片(可以先将线上图片转换成 base64,然后用 base64 作为图片路径)
不支持 flash
不支持 transform、transition 过渡、animation 动画(备注:transform 初始布局是可以的,但是不能参与动画类的操作)

3,安装配置

(1)首先到官网将 html2canvas.js 下载到本地。

官网地址:http://html2canvas.hertzen.com/

(2)然后在页面中将其引用即可。

<script type="text/javascript" src="js/html2canvas.js"></script>

二、基本用法

1,将整个页面转成 Canvas

(1)效果图
点击“开始生成”按钮后,会将整个页面渲染成一个 canvas,并将这个 canvas 添加到页面尾部。
右键点击生成的 canvas,可以将其作为图片保存到本地。
原文:JS - 使用 html2canvas 将页面保存成图片(或对指定元素截图)
(2)样例代码

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <title>hangge.com</title>
  </head>
  <body style="margin:0px">
    <div id="capture" style="padding: 10px; background: #f5da55; width: 200px;">
      <h4 style="color: #000; ">欢迎访问 hangge.com</h4>
    </div>
    <button type="button" name="button" onclick="convert()">开始生成</button>
    <br>
    <script type="text/javascript" src="js/html2canvas.js"></script>
    <script type="text/javascript">
      //开始转换
      function convert() {
        html2canvas(document.body).then(canvas => {
          document.body.appendChild(canvas)
        });
      }
    </script>
  </body>
</html>
2,将指定 DOM 元素转成 Canvas

下面样例只将按钮上方的 div 渲染成 Canvas。
原文使用 html2canvas 将页面保存成图片(或对指定元素截图)

html2canvas(document.querySelector("#capture")).then(canvas => {
  document.body.appendChild(canvas)
});
3,将 Canvas 转换成 base64 形式

(1)上面样例生成 canvas 后,便直接显示在页面上进行预览。我们也可以将生成的 canvas 转成 base64 形式用于提交到后台,或者作为 元素的 src 属性来显示。
原文使用 html2canvas 将页面保存成图片(或对指定元素截图)

html2canvas(document.querySelector("#capture")).then(canvas => {
  var imgUrl = canvas.toDataURL("image/png"); // 将canvas转换成img的src流
  console.log("base64编码数据:", imgUrl);
});

(2)转换时可以设置截图质量(0~1)

html2canvas(document.querySelector("#capture")).then(canvas => {
  var imgUrl = canvas.toDataURL("image/png", 1); // 此方法可以设置截图质量(0-1)
  console.log("base64编码数据:", imgUrl);
});

三、进阶用法

1,设置生成的 Canvas 的高度和宽度

html2canvas 在使用时还有许多可选的配置参数,下面样例生成一个 75*75 的 canvas。
原文:JS - 使用 html2canvas 将页面保存成图片(或对指定元素截图)

html2canvas(document.querySelector("#capture"),{
width: 75,
height: 75
}).then(canvas => {
document.body.appendChild(canvas)
});
2,设置 Canvas 的背景色

(1)使用 backgroundColor 这个属性可以设置 canvas 的背景色:
默认值为白色(#ffffff)
如果想要背景透明,可以将其设为 null

(2)下面将背景色改成绿色
原文:JS - 使用 html2canvas 将页面保存成图片(或对指定元素截图)

html2canvas(document.querySelector("#capture"),{
  width: 240,
  height: 120,
  backgroundColor: "#00ff00"
}).then(canvas => {
  document.body.appendChild(canvas)
});
3,设置放大倍数

(1)使用 scale 属性可以修改渲染时的放大倍数(默认为 1),将其调大可以解决低分辨率设备下生成的图片模糊问题。
(2)下面是当 scale 设置为2时,生成的图片。
原文:JS - 使用 html2canvas 将页面保存成图片(或对指定元素截图)

html2canvas(document.querySelector("#capture"),{
  scale: 2
}).then(canvas => {
  document.body.appendChild(canvas)
});
4,指定渲染的 Canvas

如果页面上原先就有个 canvas 元素,我们希望可以将图片绘制在它上面,可以使用 canvas 属性设置。
原文:JS - 使用 html2canvas 将页面保存成图片(或对指定元素截图)

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <title>hangge.com</title>
  </head>
  <body style="margin:0px">
    <div id="capture" style="padding: 10px; background: #f5da55; width: 200px;">
      <h4 style="color: #000; ">欢迎访问 hangge.com</h4>
    </div>
    <button type="button" name="button" onclick="convert()">开始生成</button>
    <br>
    <canvas id="myCanvas" width="220" height="84"></canvas>
    <script type="text/javascript" src="js/html2canvas.js"></script>
    <script type="text/javascript">
      //开始转换
      function convert() {
        html2canvas(document.querySelector("#capture"),{
          canvas: document.querySelector("#myCanvas")
        }).then(canvas => {
 
        });
      }
    </script>
  </body>
</html>
附:自动保存为图片并下载

(1)上面样例如果要将 DOM 元素变为图片保存下来,都是先将其转成 canvas,然后再手动在 canvas 上点击右键,通过“另存为”功能下载到本地。
(2)如果想要实现图片自动生成、自动下载的话可以借助 FileSaver.js 这个第三方库。其具体安装配置可以参考我之前的写的文章:
JS - 使用 FileSaver.js 实现浏览器文件导出

(3)下面是一个简单样例,点击“开始生成”按钮后,可以看到浏览器直接自动下载文件。
原文使用 html2canvas 将页面保存成图片(或对指定元素截图)

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <title>hangge.com</title>
  </head>
  <body style="margin:0px">
    <div id="capture" style="padding: 10px; background: #f5da55; width: 200px;">
      <h4 style="color: #000; ">欢迎访问 hangge.com</h4>
    </div>
    <button type="button" name="button" onclick="convert()">开始生成</button>
    <br>
    <script type="text/javascript" src="js/html2canvas.js"></script>
    <script type="text/javascript" src="js/FileSaver.js"></script>
    <script type="text/javascript">
      //开始转换
      function convert() {
        html2canvas(document.querySelector("#capture")).then(canvas => {
          //将canvas内容保存为文件并下载
          canvas.toBlob(function(blob) {
             saveAs(blob, "hangge.png");
          });
        });
      }
    </script>
  </body>
</html>

参考链接:http://www.hangge.com/blog/cache/detail_2211.html#

如果有跨域的图片,那么js报错,报错信息如下:

Uncaught SecurityError: Failed to execute ‘toDataURL’ on ‘HTMLCanvasElement’: Tainted canvases may not be exported.
解决方法:
1、利用https://tinypng.com/将图片压缩一下;
2、将图片放在服务器下就不会产生跨域问题了;
公众号:
在这里插入图片描述
微信:
在这里插入图片描述

发布了84 篇原创文章 · 获赞 102 · 访问量 4万+

猜你喜欢

转载自blog.csdn.net/allen_csdns/article/details/103420026