整合营销服务商

电脑端+手机端+微信端=数据同步管理

免费咨询热线:

JavaScript网页截屏方法,你get到了嘛?

JavaScript网页截屏方法,你get到了嘛?

前我曾写过如何将canvas图形转换成图片和下载canvas图像的方法,这些都是在为这个插件做技术准备。

技术路线很清晰,将网页的某个区域的内容生成图像,保持到canvas里,然后将canvas内容转换成图片,保存到本地,最后上传到微博。

我在网上搜寻到html2canvas这个能将指定网页元素内容生成canvas图像的javascript工具。这个js工具的用法很简单,你只需要将它的js文件引入到页面里,然后调用html2canvas()函数:

 html2canvas(document.body, {
     onrendered: function(canvas) {
         /* canvas is the actual canvas element,
            to append it to the page call for example
            document.body.appendChild( canvas );
         */
     }
 });

这个html2canvas()函数有个参数,上面的例子里传入的参数是document.body,这会截取整个页面的图像。如果你想只截取一个区域,比如对某个p或某个table截图,你就将这个p或某个table当做参数传进去。

我最终并没有选用html2canvas这个js工具,因为在我的实验过程中发现它有几个问题。

首先,跨域问题。我举个例子说明这个问题,比如我的网页网址是http://www.webhek.com/about/,而我在这个页面上有个张图片,这个图片并不是来自www.webhek.com域,而是来自CDN图片服务器www.webhek-cdn.com/images/about.jpg,那么,这张图片就和这个网页不是同域,那么html2canvas就无法对这种图片进行截图,如果你的网站的所有图片都放在单独的图片服务器上,那么用html2canvas对整个网页进行截图是就会发现所有图片的地方都是空白。

这个问题也有补救的方法,就是用代理:

 <!DOCTYPE html>
 <html>
     <head>
         <meta charset="utf-8">
         <title>html2canvas php proxy</title>
         <script src="html2canvas.js"></script>
         <script>
         //<![CDATA[
         (function() {
             window.onload=function(){
                 html2canvas(document.body, {
                     "logging": true, //Enable log (use Web Console for get Errors and Warnings)
                     "proxy":"html2canvasproxy.php",
                     "onrendered": function(canvas) {
                         var img=new Image();
                         img.onload=function() {
                             img.onload=null;
                             document.body.appendChild(img);
                         };
                         img.onerror=function() {
                             img.onerror=null;
                             if(window.console.log) {
                                 window.console.log("Not loaded image from canvas.toDataURL");
                             } else {
                                 alert("Not loaded image from canvas.toDataURL");
                             }
                         };
                         img.src=canvas.toDataURL("image/png");
                     }
                 });
             };
         })();
         //]]>
         </script>
     </head>
     <body>
         <p>
             <img alt="google maps static" src="http://maps.googleapis.com/maps/api/staticmap?center=40.714728,-73.998672&zoom=12&size=800x600&maptype=roadmap&sensor=false">
         </p>
     </body>
 </html>

这个方法只能用在你自己的服务器里,如果是对别人的网页截图,还是不行。

试验的过程中还发现用html2canvas截屏出来的图像有时会出现文字重叠的现象。我估计是因为html2canvas在解析页面内容、处理css时不是很完美的原因。

最后,我在火狐浏览器的官方网站上找到了drawWindow()这个方法,这个方法和上面提到html2canvas不同之处在于,它不分析页面元素,它只针对区域,也就是说,它接受的参数是四个数字标志的区域,不论这个区域中什么地方,有没有页面内容。

 void drawWindow(
   in nsIDOMWindow window,
   in float x, 
   in float y,
   in float w,
   in float h,
   in DOMString bgColor,
   in unsigned long flags [optional]
 );

这个原生的JavaScript方法看起来非常的完美,正是我需要的,但这个方法不能使用在普通网页中,因为火狐官方发现这个方法会引起有安全漏洞,在这个bug修复之前,只有具有“Chrome privileges”的代码才能使用这个drawWindow()函数。

虽然有很大的限制,但周折一下还是可以用的,在我开发的火狐addon插件中,main.js就是具有“Chrome privileges”的代码。我在网上发现了一段火狐插件SDK里自带代码样例:

 var window=require('window/utils').getMostRecentBrowserWindow();
 var tab=require('tabs/utils').getActiveTab(window);
 var thumbnail=window.document.createElementNS("http://www.w3.org/1999/xhtml", "canvas");
 thumbnail.mozOpaque=true;
 window=tab.linkedBrowser.contentWindow;
 thumbnail.width=Math.ceil(window.screen.availWidth / 5.75);
 var aspectRatio=0.5625; // 16:9
 thumbnail.height=Math.round(thumbnail.width * aspectRatio);
 var ctx=thumbnail.getContext("2d");
 var snippetWidth=window.innerWidth * .6;
 var scale=thumbnail.width / snippetWidth;
 ctx.scale(scale, scale);
 ctx.drawWindow(window, window.scrollX, window.scrollY, snippetWidth, snippetWidth * aspectRatio, "rgb(255,255,255)");
 // thumbnail now represents a thumbnail of the tab

这段代码写的非常清楚,只需要依据它做稍微的修改就能适应自己的需求。

这里小编是一个有着10年工作经验的前端高级工程师,关于web前端有许多的技术干货,包括但不限于各大厂的最新面试题系列、前端项目、最新前端路线等。需要的伙伴可以私信我

发送【前端资料】

就可以获取领取地址,免费送给大家。对于学习web前端有任何问题(学习方法,学习效率,如何就业)都可以问我。希望你也能凭自己的努力,成为下一个优秀的程序员

过上一章的内容,现在网页文件中,我们还须要去除的就是html代码了。

下面我们要研究一下html代码的主要特点,不管什么样的HTML代码,他们均被左右尖括号所包围,就像这个样子<代码>,因此,我们就有了去除的方法,把括号中的内容和联通括号一起去除掉,就可以了。

下面开始,根据我们的想法,可以写出,下面这样的主程序

看上图,再上一张定义的函数,我们把它移动到了通用函数库中

第21行,这是我们新增的代码,执行完这个代码,就去除掉了HTML标记,剩下的就应该是纯文字内容了。在这里,我们定义了一个函数,名字叫做去除html代码

下面我们研究一下,这个函数的内容,如下图

因为使用了正则表达式,因此,在程序运行前,必须导入模块re

第3行,导入我们所需要的re模块,我们想用到正则表达式

第5行,定义函数

第6行,用右尖括号分格隔成列表

第8行,对列表元素进行遍历

第9行,使用正则挑出有效的内容,其实就是去除以前孤立的右尖括号的内容。

第10行,对有效的内容进行左尖括号分隔

第11行,左尖括号前面的内容就是有效的文字内容

完整的程序如下

下面我们对程序进行下测试,在上一章中,程序运行后得到如下的内容(内容太长,只截取一小部分)

本次程序改造后,运行得到下面的内容


从上面两个图片可以看出,我们确实把文字内容提取出来了。

最近再做一个需求,需要对网页生成预览图,如下图


但是网页千千万,总不能一个个打开,截图吧;于是想着能不能使用代码来实现网页的截图。其实要实现这个功能,无非就是要么实现一个仿真浏览器,要么调用系统浏览器,再进行截图操作。

代码实现

1、启用线程Thread

  •  void startPrintScreen(ScreenShotParam requestParam) { Thread thread=new Thread(new ParameterizedThreadStart(do_PrintScreen)); thread.SetApartmentState(ApartmentState.STA); thread.Start(requestParam); if (requestParam.Wait) { thread.Join(); FileInfo result=new FileInfo(requestParam.SavePath); long minSize=1 * 1024;// 太小可能是空白圖,重抓 int maxRepeat=2;  while ((!result.Exists || result.Length <=minSize) && maxRepeat > 0) { thread=new Thread(new ParameterizedThreadStart(do_PrintScreen)); thread.SetApartmentState(ApartmentState.STA); thread.Start(requestParam); thread.Join(); maxRepeat--; } } }

    2、模拟浏览器WebBrowser

    •  void do_PrintScreen(object param) { try { ScreenShotParam screenShotParam=(ScreenShotParam)param; string requestUrl=screenShotParam.Url; string savePath=screenShotParam.SavePath; WebBrowser wb=new WebBrowser(); wb.ScrollBarsEnabled=false; wb.ScriptErrorsSuppressed=true; wb.Navigate(requestUrl); logger.Debug("wb.Navigate"); DateTime startTime=DateTime.Now; TimeSpan waitTime=new TimeSpan(0, 0, 0, 10, 0);// 10 second while (wb.ReadyState !=WebBrowserReadyState.Complete) { Application.DoEvents(); if (DateTime.Now - startTime > waitTime) { wb.Dispose(); logger.Debug("wb.Dispose() timeout"); return; } }
      wb.Width=screenShotParam.Left + screenShotParam.Width + screenShotParam.Left; // wb.Document.Body.ScrollRectangle.Width (避掉左右側的邊線); wb.Height=screenShotParam.Top + screenShotParam.Height; // wb.Document.Body.ScrollRectangle.Height; wb.ScrollBarsEnabled=false; wb.Document.Body.Style="overflow:hidden";//hide scroll bar var doc=(wb.Document.DomDocument) as mshtml.IHTMLDocument2; var style=doc.createStyleSheet("", 0); style.cssText=@"img { border-style: none; }";
      Bitmap bitmap=new Bitmap(wb.Width, wb.Height); wb.DrawToBitmap(bitmap, new Rectangle(0, 0, wb.Width, wb.Height)); wb.Dispose(); logger.Debug("wb.Dispose()");
      bitmap=CutImage(bitmap, new Rectangle(screenShotParam.Left, screenShotParam.Top, screenShotParam.Width, screenShotParam.Height)); bool needResize=screenShotParam.Width > screenShotParam.ResizeMaxWidth || screenShotParam.Height > screenShotParam.ResizeMaxWidth; if (needResize) { double greaterLength=bitmap.Width > bitmap.Height ? bitmap.Width : bitmap.Height; double ratio=screenShotParam.ResizeMaxWidth / greaterLength; bitmap=Resize(bitmap, ratio); }
      bitmap.Save(savePath, System.Drawing.Imaging.ImageFormat.Gif); bitmap.Dispose(); logger.Debug("bitmap.Dispose();"); logger.Debug("finish");
      } catch (Exception ex) { logger.Info($"exception: {ex.Message}"); } }

      3、截图操作

      •  private static Bitmap CutImage(Bitmap source, Rectangle section) { // An empty bitmap which will hold the cropped image Bitmap bmp=new Bitmap(section.Width, section.Height); //using (Bitmap bmp=new Bitmap(section.Width, section.Height)) { Graphics g=Graphics.FromImage(bmp);
        // Draw the given area (section) of the source image // at location 0,0 on the empty bitmap (bmp) g.DrawImage(source, 0, 0, section, GraphicsUnit.Pixel);
        return bmp; } }
        private static Bitmap Resize(Bitmap originImage, Double times) { int width=Convert.ToInt32(originImage.Width * times); int height=Convert.ToInt32(originImage.Height * times);
        return ResizeProcess(originImage, originImage.Width, originImage.Height, width, height); }

        完整代码


        •  public static string ScreenShotAndSaveAmazonS3(string account, string locale, Guid rule_ID, Guid template_ID) {  //新的Template var url=string.Format("https://xxxx/public/previewtemplate?showTemplateName=0&locale={0}&inputTemplateId={1}&inputThemeId=&Account={2}", locale, template_ID, account ); 
          var tempPath=Tools.GetAppSetting("TempPath");
          //路徑準備 var userPath=AmazonS3.GetS3UploadDirectory(account, locale, AmazonS3.S3SubFolder.Template); var fileName=string.Format("{0}.gif", template_ID); var fullFilePath=Path.Combine(userPath.LocalDirectoryPath, fileName); logger.Debug("userPath: {0}, fileName: {1}, fullFilePath: {2}, url:{3}", userPath, fileName, fullFilePath, url); //開始截圖,並暫存在本機 var screen=new Screen(); screen.ScreenShot(url, fullFilePath);
          //將截圖,儲存到 Amazon S3 //var previewImageUrl=AmazonS3.UploadFile(fullFilePath, userPath.RemotePath + fileName);
          return string.Empty; }


          • using System;using System.Collections.Generic;using System.Drawing;using System.IO;using System.Linq;using System.Text;using System.Threading;using System.Threading.Tasks;using System.Windows.Forms;
            namespace PrintScreen.Common{ public class Screen { protected static NLog.Logger logger=NLog.LogManager.GetCurrentClassLogger();
            public void ScreenShot(string url, string path , int width=400, int height=300 , int left=50, int top=50 , int resizeMaxWidth=200, int wait=1) { if (!string.IsOrEmpty(url) && !string.IsOrEmpty(path)) { ScreenShotParam requestParam=new ScreenShotParam { Url=url, SavePath=path, Width=width, Height=height, Left=left, Top=top, ResizeMaxWidth=resizeMaxWidth, Wait=wait !=0 }; startPrintScreen(requestParam); } }
            void startPrintScreen(ScreenShotParam requestParam) { Thread thread=new Thread(new ParameterizedThreadStart(do_PrintScreen)); thread.SetApartmentState(ApartmentState.STA); thread.Start(requestParam); if (requestParam.Wait) { thread.Join(); FileInfo result=new FileInfo(requestParam.SavePath); long minSize=1 * 1024;// 太小可能是空白圖,重抓 int maxRepeat=2; while ((!result.Exists || result.Length <=minSize) && maxRepeat > 0) { thread=new Thread(new ParameterizedThreadStart(do_PrintScreen)); thread.SetApartmentState(ApartmentState.STA); thread.Start(requestParam); thread.Join(); maxRepeat--; } } }
            void do_PrintScreen(object param) { try { ScreenShotParam screenShotParam=(ScreenShotParam)param; string requestUrl=screenShotParam.Url; string savePath=screenShotParam.SavePath; WebBrowser wb=new WebBrowser(); wb.ScrollBarsEnabled=false; wb.ScriptErrorsSuppressed=true; wb.Navigate(requestUrl); logger.Debug("wb.Navigate"); DateTime startTime=DateTime.Now; TimeSpan waitTime=new TimeSpan(0, 0, 0, 10, 0);// 10 second while (wb.ReadyState !=WebBrowserReadyState.Complete) { Application.DoEvents(); if (DateTime.Now - startTime > waitTime) { wb.Dispose(); logger.Debug("wb.Dispose() timeout"); return; } }
            wb.Width=screenShotParam.Left + screenShotParam.Width + screenShotParam.Left; // wb.Document.Body.ScrollRectangle.Width (避掉左右側的邊線); wb.Height=screenShotParam.Top + screenShotParam.Height; // wb.Document.Body.ScrollRectangle.Height; wb.ScrollBarsEnabled=false; wb.Document.Body.Style="overflow:hidden";//hide scroll bar var doc=(wb.Document.DomDocument) as mshtml.IHTMLDocument2; var style=doc.createStyleSheet("", 0); style.cssText=@"img { border-style: none; }";
            Bitmap bitmap=new Bitmap(wb.Width, wb.Height); wb.DrawToBitmap(bitmap, new Rectangle(0, 0, wb.Width, wb.Height)); wb.Dispose(); logger.Debug("wb.Dispose()");
            bitmap=CutImage(bitmap, new Rectangle(screenShotParam.Left, screenShotParam.Top, screenShotParam.Width, screenShotParam.Height)); bool needResize=screenShotParam.Width > screenShotParam.ResizeMaxWidth || screenShotParam.Height > screenShotParam.ResizeMaxWidth; if (needResize) { double greaterLength=bitmap.Width > bitmap.Height ? bitmap.Width : bitmap.Height; double ratio=screenShotParam.ResizeMaxWidth / greaterLength; bitmap=Resize(bitmap, ratio); }
            bitmap.Save(savePath, System.Drawing.Imaging.ImageFormat.Gif); bitmap.Dispose(); logger.Debug("bitmap.Dispose();"); logger.Debug("finish");
            } catch (Exception ex) { logger.Info($"exception: {ex.Message}"); } }
            private static Bitmap CutImage(Bitmap source, Rectangle section) { // An empty bitmap which will hold the cropped image Bitmap bmp=new Bitmap(section.Width, section.Height); //using (Bitmap bmp=new Bitmap(section.Width, section.Height)) { Graphics g=Graphics.FromImage(bmp);
            // Draw the given area (section) of the source image // at location 0,0 on the empty bitmap (bmp) g.DrawImage(source, 0, 0, section, GraphicsUnit.Pixel);
            return bmp; } }
            private static Bitmap Resize(Bitmap originImage, Double times) { int width=Convert.ToInt32(originImage.Width * times); int height=Convert.ToInt32(originImage.Height * times);
            return ResizeProcess(originImage, originImage.Width, originImage.Height, width, height); }
            private static Bitmap ResizeProcess(Bitmap originImage, int oriwidth, int oriheight, int width, int height) { Bitmap resizedbitmap=new Bitmap(width, height); //using (Bitmap resizedbitmap=new Bitmap(width, height)) { Graphics g=Graphics.FromImage(resizedbitmap); g.InterpolationMode=System.Drawing.Drawing2D.InterpolationMode.High; g.SmoothingMode=System.Drawing.Drawing2D.SmoothingMode.HighQuality; g.Clear(Color.Transparent); g.DrawImage(originImage, new Rectangle(0, 0, width, height), new Rectangle(0, 0, oriwidth, oriheight), GraphicsUnit.Pixel); return resizedbitmap; } }
            }
            class ScreenShotParam { public string Url { get; set; } public string SavePath { get; set; } public int Width { get; set; } public int Height { get; set; } public int Left { get; set; } public int Top { get; set; } /// <summary> /// 長邊縮到指定長度 /// </summary> public int ResizeMaxWidth { get; set; } public bool Wait { get; set; } }
            }

            效果

            完成,达到预期的效果。