Using JavaScript to take screenshots, here I would like to recommend two open source components: one is Canvas2Image, which can program Canvas drawing into PNG/JPEG/BMP images; but it is not enough alone, we need to give To take a screenshot of any DOM (at least most of it), you need html2canvas, which can convert the DOM object into a canvas object. Combining the functions of the two, you can screenshot the DOM on the page into a PNG or JPEG image, which is very cool.
Canvas2Image
The principle is to use the HTML5 canvas object to provide the toDataURL() API:
Such a result is base64 encoded (in fact, the image can also be written to the page in the form of a string in this way), so we also need a base64 encoding and decoding lib.
However, there are many current flaws. For example, Opera and Safari currently only support PNG, while FireFox has much better support.
There are two ways to generate images and write them into the page. One is to generate an image object and write it into the page DOM tree. This is also a more supportive way:
html2canvas
It acts on the DOM loading process, collects the information, and then draws the canvas image. In other words, it does not actually cut the displayed DOM tree into a canvas image, but redraws a canvas based on the DOM tree. picture. Therefore, many CSS styles cannot be accurately recognized and cannot be accurately reflected on the image.
There are many other restrictions, such as:
●Javascript must be in the same domain. For cross-domain situations, a proxy server needs to be used (there are parameters in the API that can be specified). The same is true for images;
●The DOM tree within the frame cannot be drawn accurately;
●Because the drawing is a canvas, browsers like IE8 need to use third-party libraries such as FlashCanvas.
This page can test the effect of various websites using it to take screenshots, and the effect is quite good:
Examples of API usage:
For this relatively niche class library, the documentation is very poor, including the definition of the API. You need to read the source code, and the code is clearly written.
In addition, there is a JQuery plug-in in the download package of this site, which encapsulates this API and can be ignored.