使用 html2canvas 将页面保存成图片

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

关注我的微信公众号【前端基础教程从0开始】,加我微信,可以免费为您解答问题。回复“1”,拉你进程序员技术讨论群。回复“小程序”,领取300个优秀的小程序开源代码+一套入门教程。回复“领取资源”,领取300G前端,Java,微信小程序,Python等资源,让我们一起学前端。

一、基本介绍

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 将页面保存成图片(或对指定元素截图)
1
2
3
4
5
6
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、将图片放在服务器下就不会产生跨域问题了;

JavaScript HTML renderer The script allows you to take "screenshots" of webpages or parts of it, directly on the users browser. The screenshot is based on the DOM and as such may not be 100% accurate to the real representation as it does not make an actual screenshot, but builds the screenshot based on the information available on the page. How does it work? The script renders the current page as a canvas image, by reading the DOM and the different styles applied to the elements. It does not require any rendering from the server, as the whole image is created on the clients browser. However, as it is heavily dependent on the browser, this library is not suitable to be used in nodejs. It doesn't magically circumvent any browser content policy restrictions either, so rendering cross-origin content will require a proxy to get the content to the same origin. The script is still in a very experimental state, so I don't recommend using it in a production environment nor start building applications with it yet, as there will be still major changes made. Browser compatibility The script should work fine on the following browsers: Firefox 3.5+ Google Chrome Opera 12+ IE9+ Safari 6+ As each CSS property needs to be manually built to be supported, there are a number of properties that are not yet supported. Usage Note! These instructions are for using the current dev version of 0.5, for the latest release version (0.4.1), checkout the old readme. To render an element with html2canvas, simply call: html2canvas(element[, options]); The function returns a Promise containing the <canvas> element. Simply add a promise fullfillment handler to the promise using then: html2canvas(document.body).then(function(canvas) { document.body.appendChild(canvas); }); Building The library uses grunt for building. Alternatively, you can download the latest build from here. Clone git repository with submodules: $ git clone --recursive git://github.com/niklasvh/html2canvas.git Install Grunt and uglifyjs: $ npm install -g grunt-cli uglify-js Run the full build process (including lint, qunit and webdriver tests): $ grunt Skip lint and tests and simply build from source: $ grunt build Running tests The library has two sets of tests. The first set is a number of qunit tests that check that different values parsed by browsers are correctly converted in html2canvas. To run these tests with grunt you'll need phantomjs. The other set of tests run Firefox, Chrome and Internet Explorer with webdriver. The selenium standalone server (runs on Java) is required for these tests and can be downloaded from here. They capture an actual screenshot from the test pages and compare the image to the screenshot created by html2canvas and calculate the percentage differences. These tests generally aren't expected to provide 100% matches, but while commiting changes, these should generally not go decrease from the baseline values. Start by downloading the dependencies: $ npm install Run qunit tests: $ grunt test Examples For more information and examples, please visit the homepage or try the test console. Contributing If you wish to contribute to the project, please send the pull requests to the develop branch. Before submitting any changes, try and test that the changes work with all the support browsers. If some CSS property isn't supported or is incomplete, please create appropriate tests for it as well before submitting any code changes.
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值