html5 实现网页截屏 页面生成图片(图文)

html5 实现网页截屏 页面生成图片(图文)

html5 实现网页截屏 页面生成图片(图文)
分类: html 2014-04-04 15:19 6039人阅读 评论(0) 收藏 举报
html2canvas通过获取页面的DOM和元素的样式信息,并将其渲染成canvas图片,从而实现给页面截图的功能。

因为每个浏览器渲染页面的方式都不尽相同,所以生成的图片也不太一样。

环境要求: jQuery
兼容性: Firefox 3.5+, Chrome, Opera, IE9

官网主页: http://html2canvas.hertzen.com/

测试生成的图片效果 有些元素的样式没有完全展示出来

js插件 实现网页截屏 页面生成图片
[html] view plaincopy在CODE上查看代码片派生到我的代码片
<html>  
    <head>  
        <meta name="layout" content="main">  
        <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />    
        <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>  
        <script type="text/javascript" src="http://html2canvas.hertzen.com/build/html2canvas.js"></script>  
           
        <script  type="text/javascript" >  
        $(document).ready( function(){  
                $(".example1").on("click", function(event) {  
                        event.preventDefault();  
                        html2canvas(document.body, {  
                        allowTaint: true,  
                        taintTest: false,  
                        onrendered: function(canvas) {  
                            canvas.id = "mycanvas";  
                            //document.body.appendChild(canvas);  
                            //生成base64图片数据  
                            var dataUrl = canvas.toDataURL();  
                            var newImg = document.createElement("img");  
                            newImg.src =  dataUrl;  
                            document.body.appendChild(newImg);  
                        }  
                    });  
                });   
               
        });  
           
        </script>  
    </head>  
    <body>  
           
        Hello!  
        <div class="" style="background-color: #abc;">  
            计算机天堂测试html5页面截图  
            <br>jsjtt.com  
        </div>  
           
        <textArea id="textArea" col="20" rows="10" ></textArea>  
        <input class="example1" type="button" value="button">  
        生成界面如下:  
    </body>  
</html>  

说明在测试过程中出现的问题如果页面上引用跨域的图片文件调用toDataURL的时候会出错

SecurityError: The operation is insecure.  

解决方法:在跨域的服务器上设置header设置为允许跨域请求

[html] view plaincopy在CODE上查看代码片派生到我的代码片
access-control-allow-origin: *  access-control-allow-credentials: true  


原始地址:计算机天堂---html5 实现网页截屏 页面生成图片    http://www.jsjtt.com/webkaifa/html5/2013-10-29/42.html