Web开发之html2canvas 实现纯JS网页截图简单例子

       代码库地址: https://github.com/niklasvh/html2canvas

       自己修改其中的 test.js (主要是其中的一些库的路径) 把test.js external文件夹 src文件夹 放在同一目录下

  var h2cSelector, h2cOptions;
  (function(document, window) {
      var scrStart = '<script type="text/javascript" src="', scrEnd = '"></script>';
      document.write(scrStart + 'external/jquery-1.6.2.js' + scrEnd);
      var html2canvas = ['Core', 'Generate', 'Parse', 'Preload', 'Queue', 'Renderer', 'Util', 'renderers/Canvas',  'plugins/jquery.plugin.html2canvas'], i;
      for (i = 0; i < html2canvas.length; ++i) {
          document.write(scrStart + 'src/' + html2canvas[i] + '.js' + scrEnd);
      }
      window.onload = function() {
         h2cSelector = [document.body];

         if (window.setUp) {
             window.setUp();
         }


     };
 }(document, window));

 function screenShot()
 {
     setTimeout(function() {
             $(h2cSelector).html2canvas($.extend({
                 flashcanvas: "external/flashcanvas.min.js",
                 logging: true,
                 profile: true,
                 useCORS: true,
                 onrendered:function(canvas )
                 {
                     var screenshot;
                     screenshot = canvas.toDataURL( "image/png" );
                     console.info(screenshot);
                 }
             }, h2cOptions));
         }, 100);
 }

       在主页中包含 test.js 然后调用 screenshot 函数就可以在控制台看到图片了,该数据可以上传至服务器。

===========================================================================

       使用JavaScript截图,这里我要推荐两款开源组件:一个是Canvas2Image,它可以将Canvas绘图编程PNG/JPEG/BMP的图像;但是光有它还不够,我们需要给任意DOM(至少是绝大部分)截图,这就需要html2canvas,它可以将DOM对象转换成一个canvas对象。两者的功能结合起来,就可以把页面上的DOM截图成PNG或者JPEG图像了,很酷。

Canvas2Image

       它的原理是利用了HTML5的canvas对象提供了toDataURL()的API:

var strDataURI = oCanvas.toDataURL(); 

// returns "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAMgAAADICAYAAACt..."

       这样的结果是base64编码的(事实上,image也可以通过这种方式以字符串的形式写死到页面上),所以我们还需要一个base64编解码的lib。

       但是目前的缺陷也有不少,比如目前Opera和Safari只支持PNG,FireFox的支持性则好得多。

       生成图片有两种方式写入页面,一种是生成一个图片对象写入页面DOM树中,这也是支持性比较好的方式:

// returns an <img> element containing the converted PNG image 

var oImgPNG = Canvas2Image.saveAsPNG(oCanvas, true);

       但是如果你做一个JavaScript截图功能的话,你可能希望截图后能够自动打开保存文件的“保存”对话框:

Canvas2Image.saveAsPNG(oCanvas);

// will prompt the user to save the image as PNG.

       这个方式调用会生成一个mimeType“image/octet-stream”的数据流到浏览器,但是“保存”对话框无法识别出图片适当的后缀名,默认保存的文件在FireFox下是“xxx.part”这种名字,这是令人遗憾的地方,但是似乎没有什么好办法解决。

html2canvas

       它作用于DOM加载的过程,收集其中的信息,再来绘制canvas图像,也就是说,其实它并不是将展现的DOM树截成canvas图,而是仿照DOM树重新绘制了一张canvas图。于是很多CSS样式都无法被准确识别出来,无法准确反映到图上。

       其它的限制还有不少,比如:

       javascript必须是同域的,对于跨域的情况需要使用代理服务器(API中有参数可以指定),对于image也同样;

       frame内的DOM树无法被准确绘制;

       因为要绘制的是canvas图,所以像IE8这样的浏览器需要使用FlashCanvas这样的第三方库。
这个页面可以测试各个网站使用它来截图的效果,效果相当不错:

用JavaScript截图

       API使用的例子:

html2canvas(

    [dom1, dom2],

    {

        logging: false,

        useCORS: false,

        proxy:   false,

        onrendered: function(canvas){

            // canvas 就是绘制的canvas是对象

        }

    }

);

       对于这一类相对小众的类库,文档都是很差的,包括API的定义,需要阅读源码,代码上写得挺清楚的。

       另外,该站点下载包里面还有一个JQuery的插件,对这个API做了一个封装,可以无视。

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.
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值