The html2canvas front end saves the page as a picture

html2canvas

Preface: The front end saves the page as a picture. The most common solution is to use html2canvas to generate pictures.

The application scenario
PM requires that some awards won by the company's subsidiaries... be displayed on the front end as required; and the partial saved pictures of the H5 page should be shared.

Solution: html2canvas
use:

  1. npm install --save html2canvas
  2. Introduce html2canvas into componentsimport html2canvas from "html2canvas"

Specifically:
Take the local dom node as the drawing of the converted image: <div ref="canvasImgObj" class="jiangzhuang-item">
canvasImgObj needs to be the parent container of the page content you want to convert, that is, all the page content you want to convert must be contained in the imageDom node.
The conversion method is as follows:

/**
* 将页面指定节点内容转为图片
* 1.拿到想要转换为图片的内容节点DOM;
* 2.转换,拿到转换后的canvas
* 3.转换为图片
*/
// 生成局部图片
GenerateImg() {
  let element = this.$refs.canvasImgObj;
  // console.warn(element);
  html2canvas(element[this.slideIndex], { // 我这里是一个swiper,要是一个页面的话直接element就行
    allowTaint: true,
    useCORS: true,
    tainttest: true, // 检测每张图片都已经加载完成
    logging: true,
    backgroundColor: `rgb(143,40,37)`, // 转换图片可能会有白色底色,你可根据你的页面或者PM要求设置一下背景色,不要的话就null
  }).then((canvas) => {
    //  转成图片,生成图片地址
    let imgUrl = canvas.toDataURL("image/jpeg");
    console.warn(imgUrl); 
  });
}

  • At this point, you have drawn a certain node area on the H5 page as a picture, and you may find that the drawn picture is more or less blurry. Here, it is recommended to replace all the background pictures involved in the node area for rendering.

download:

// 创建隐藏的可下载链接
let eleLink = document.createElement("a");
eleLink.href = imgUrl; // 转换后的图片地址
eleLink.download = "pictureName";
// 触发点击
document.body.appendChild(eleLink);
eleLink.click();
// 然后移除
document.body.removeChild(eleLink);

What needs to be noted here is: although the download attribute of the a tag can be downloaded, it is not compatible and many do not support it. It can still be used even if the browser is not compatible, such as Chrome.
Therefore, it is recommended to provide a native interface for the mobile terminal. In addition, you can make a guide, such as a series of operations such as long press to save in WeChat.

insert image description here

Finally, when developing H5, once WeChat is considered, there may be some problems and limitations that were not considered before. For this, product managers and programmers should learn as much as possible. Know what you can and cannot do in WeChat, and reduce the cost of development and repeated communication.

Guess you like

Origin blog.csdn.net/qq_43531694/article/details/112775030