Home  >  Article  >  Web Front-end  >  Learn how to take screenshots of Javascript web pages together

Learn how to take screenshots of Javascript web pages together

coldplay.xixi
coldplay.xixiforward
2020-06-19 16:59:552114browse

Learn how to take screenshots of Javascript web pages together

I have previously written about how to convert canvas graphics into images and how to download canvas images. These are all technical preparations for this plug-in.

The technical route is very clear. Generate an image from the content of a certain area of ​​the web page and save it to the canvas. Then convert the canvas content into an image, save it locally, and finally upload it to Weibo.

I searched on the Internet and found html2canvas, a javascript tool that can generate canvas images from the content of specified web page elements. The usage of this js tool is very simple. You only need to introduce its js file into the page, and then call the html2canvas() function:

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 );
        */
    }
});

Thishtml2canvas()The function has a parameter. In the above example, the parameter passed in is document.body, which will capture the image of the entire page. If you want to capture only one area, such as taking a screenshot of a certain p or a certain table, you can take a screenshot of this p or a certain table Pass it in as a parameter.

I ultimately did not choose the js tool html2canvas because I found several problems with it during my experiment.

First of all, cross-domain issues. Let me give an example to illustrate this problem. For example, my webpage URL is http://www.webhek.com/about/, and I have a picture on this page. This picture does not come from the www.webhek.com domain. It comes from the CDN image server www.webhek-cdn.com/images/about.jpg. Then, this image is not in the same domain as this webpage, so html2canvas cannot take screenshots of this kind of image. If all of your website The images are placed on a separate image server. If you use html2canvas to take a screenshot of the entire web page, you will find that all images are blank.

There is also a remedy for this problem, which is to use a proxy:

<!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>

This method can only be used in your own server. If you are taking a screenshot of someone else's web page, it still won't work.

During the experiment, we also found that images captured using html2canvas sometimes have overlapping text. I guess it's because html2canvas is not perfect when parsing page content and processing css.

Finally, I found the drawWindow() method on the official website of Firefox. The difference between this method and the html2canvas mentioned above is that it does not analyze page elements. Only for areas, that is to say, the parameters it accepts are the areas marked by four numbers, no matter where in this area there is page content.

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]
);

This native JavaScript method looks perfect and is exactly what I need. However, this method cannot be used in ordinary web pages because Firefox officially found that this method will cause security holes. This bug is fixed. Previously, only code with "Chrome privileges" could use this drawWindow() function.

Although there are great limitations, it can still be used with some twists and turns. In the Firefox addon plug-in I developed, main.js is the code with "Chrome privileges". I found a code sample that comes with the Firefox plug-in SDK on the Internet:

var window = require(&#39;window/utils&#39;).getMostRecentBrowserWindow();
var tab = require(&#39;tabs/utils&#39;).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

This code is very clearly written, and you only need to make slight modifications based on it to adapt to your needs.

Recommended tutorial: "javascript video tutorial"

The above is the detailed content of Learn how to take screenshots of Javascript web pages together. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:webhek.com. If there is any infringement, please contact admin@php.cn delete