html2canvas achieve page screenshot

Documentation:
https://html2canvas.hertzen.com/

installation

npm install --save html2canvas

Simple examples

<template>
  <div id="capture" style="padding: 10px; background: #f5da55">
    <h4 style="color: #000; ">Hello world!</h4>
    <button @click="screenshots">screenshots</button>
  </div>
</template>
 
<script>
import html2canvas from "html2canvas";

export default {
  methods: {
    screenshots() {
      html2canvas(document.querySelector("#capture")).then(canvas => {
        document.body.appendChild(canvas);
      });
    }
  }
};
</script> 

Right-generated pictures can be saved
Here Insert Picture Description

In vue project code can be used if incomplete screenshots

<template>
  <div
    id="capture"
    ref="imageDom"
    style="padding: 10px; background: #f5da55;height:1000px;width100%"
  >
    <h4 style="color: #000;">Hello world!</h4>
    <button @click="screenshots">screenshots</button>
  </div>
</template>
 
<script>
import html2canvas from "html2canvas";

export default {
  methods: {
    screenshots() {
      let imageDom = this.$refs.imageDom;
      var width = imageDom.style.width;
      var cloneDom = imageDom.cloneNode(true);

      // 设置参数
      cloneDom.style.padding = "16px";
      cloneDom.style.position = "absolute";
      cloneDom.style.top = "0px";
      cloneDom.style.zIndex = "-1";
      cloneDom.style.width = width;

      document.body.appendChild(cloneDom);

      html2canvas(cloneDom).then(canvas => {
        // 转成图片,生成图片地址
        var imgUrl = canvas.toDataURL("image/png");

        var eleLink = document.createElement("a");
        eleLink.href = imgUrl; // 转换后的图片地址
        eleLink.download = "pictureName";
        // 触发点击
        document.body.appendChild(eleLink);
        eleLink.click();
        // 然后移除
        document.body.removeChild(eleLink);
      });

      cloneDom.style.display = "none";
    }
  }
};
</script> 
Released 1432 original articles · won praise 380 · Views 1.34 million +

Guess you like

Origin blog.csdn.net/mouday/article/details/104621588