How does the front end realize the one-click screenshot function?

Wonderful review

Preface

The web screenshot function is also a very common requirement, especially in the field of online education. WeChat posters and event posters in our circle of friends are generally designed by operation/marketing personnel through design tools, but how to better map to yourself In the service system, such as the H5 page, more information collection and interactive capabilities are implanted. This application exploration, page screenshots are a very good solution.

Next, I will review how to generate page posters based on web pages with one click, and integrate this ability into my open source project H5-Dooring to empower the editor.

text

Before implementing specific functions, let's take a look at the specific implementation effects: 

 From the demonstration, we can see that our ultimate goal is to generate screenshots of H5 pages on the PC side, so the following issues may be involved:

  • How to convert pages into pictures

  • How to realize the H5 effect simulation and intercept the actual H5 page

We can first think about the realization of ideas, how can we convert to pictures based on dom? This technology is also a commonplace topic, we all know that it can be implemented with canvas, the general process is as follows: 

If we use the native implementation scheme, we generally have to go through the above steps. The second step is the key link and the most complicated step. We need to manually implement the mapping from dom to canvas, and finally convert it into a standard canvas drawing object. Of course, ready-made There are also many libraries that can directly help us simplify this step, such as html2canvas, dom-to-image. Next we will solve the first problem.

How to convert pages into pictures

In the process of personally investigating and using the html2canvas library, the author found many problems, such as if% units appear in the style, or there are some problems with the background of the picture, resulting in html2canvas not working well, and rendering reduction and clarity There are problems, so the author has not studied in depth for the time being (but these problems can be solved by modifying the library itself). Later, the author directly used dom-to-image, and found that it is very simple to use, and there are almost no problems mentioned above. Therefore, the author decisively adopted dom-to-image. After reading the source code of the library, I feel that the writing is also very elegant and easy to understand. The secondary development should not be a big problem in the later period. We can look at the basic use of its official website:

// 引入
import domtoimage from 'dom-to-image';

// 生成图片
domtoimage.toPng(node)
    .then(function (dataUrl) {
        var img = new Image();
        img.src = dataUrl;
        document.body.appendChild(img);
    })
    .catch(function (error) {
        console.error('oops, something went wrong!', error);
    });

The usage is also very simple, and it provides enough configuration items for us to configure flexibly. 

The first problem is solved in this way, but the problem of blurry pictures is found during use. There are also many solutions on this Internet. For example, first zoom in dom, and zoom out when processed into canvas and finally generate pictures. This is the author I will not give examples one by one.

How to realize the H5 effect simulation and intercept the actual H5 page

Because the H5 pages we designed are all completed on the PC side, if you want to generate the H5 preview image, it is nothing more than a local simulation size for rendering. The specific plan is as follows:

  • Use iframe as H5 page container to generate screenshots

  • Directly limit the width to generate a screenshot on the current page

  • Use server crawler to simulate mobile phone access to generate screenshots

You can try all the solutions mentioned above. The author has also open sourced the crawler application to solve this problem before. If you are interested, you can study and understand. Obviously, we will choose the first solution to implement it, as in the demonstration. The H5 in the pop-up window we see is actually rendered in the iframe: the   realization idea is there, and the problem is well realized. We only need to implement message communication between the parent page and the iframe, such as when the iframe is loaded. Then manually notify the iframe to intercept itself. The basic implementation code is as follows:

// 编辑器页面, 也就是父页面
// 定义截图子页面句柄函数
window.getFaceUrl = (url) => {
  setFaceUrl(url)
  setShowModalIframe(false)
}

// iframe页面, 也就是预览页面
const generateImg = (cb:any) => {
    domtoimage.toBlob(refImgDom.current, 
      {
        width,
        height,
      }
    )
    .then(function (blob:Blob) {
        const formData = new FormData();
        formData.append('file', blob, 'tpl.jpg');
        req.post('/files/upload/free', formData).then((res:any) => {
          cb && cb(res.url)
        })
    })
    .catch(function (error:any) {
        console.error('oops, something went wrong!', error);
    });
}

// 触发父页面的方法,将图片传给父页面
generateImg((url:string) => {
  parent.window.getFaceUrl(url);
})

At last

The author of the above tutorial has been integrated into H5-Dooring. For some more complex interactive functions, it can also be realized through reasonable design. You can explore and study by yourself.

github search: H5-Dooring

If you want to learn more H5 games, webpack, node, gulp, css3, javascript, nodeJS, canvas data visualization and other front-end knowledge and actual combat, welcome to study and discuss together in "Interesting Frontend" to explore the front-end boundary together.

Guess you like

Origin blog.csdn.net/KlausLily/article/details/109881851