Recently, I received a demand to implement page screenshot in a small program. At first, I thought of using the extension component WXML-to-Canvas provided by the government, but the effect was very bad in practice. First of all, it cannot capture the actual page, but must pass in WXML and WXSS. And then there are very few effects that he can support, and they don’t satisfy the slightly more complex effects that are required. Finally, I decided to use the HTML2Canvas in the web page loaded with Web-View to achieve the function.

The actual code

I used Vue for the web part. First I need to install HTML2Canvas

npm install html2canvas

Introducing into the page

import html2canvas from 'html2canvas';

Add the ref attribute on the DOM node that requires the screenshot

<div ref="page">

Screenshot of the code

. document.body.scrollTop = 0; Html2Canvas (this.$refs. Page, {allowTaint: false, useCorors: true, width: : document.body.scrollWidth, height: Document. Body. ScrollHeight / / found in practical experience best set wide high to width of the page to obtain the complete screenshot}). Then (canvas = > {enclosing savedPic = Canvas. ToDataurl ('images/ PNG ') // The URL used to display the screenshot completed in the page... Let a = document.createElement('a'); let a = document.createElement('a'); let a = document.createElement('a'); blob = this.dataURLToBlob(canvas.toDataURL('images/png')); a.setAttribute('href', URL.createObjectURL(blob)); a.setAttribute('download', 'pic.png'); document.body.appendChild(a);; URL.revokeObjectURL(blob); document.body.removeChild(a); }); .


Web page isn’t a native small programs, or do some compatibility problems, such as a web page cannot use the small program wx. SaveImageToPhotosAlbum directly generate good screenshots. The mobile terminal and WeChat do not support clicking the simulated A tag to download pictures, and the function of saving pictures can only be realized by displaying the generated screenshots and prompting the user to press the picture long. The user experience will be poor, but considering that the screenshot effect is much better than WXML-to-Canvas, it is still acceptable.

Finally, let’s talk about the support of HTML2Canvas. So far, I have found that the unsupported styles are shadows and pseudo elements, but basically everything else is supported. The images in the web page must be local images or support cross-domain network images. It is recommended to use the img tag directly instead of the background image. The image displayed by the img tag is much clearer than the background image.