使用 html2canvas 插件通过 id 对元素截图

时间:2022-11-06 01:04:49

一、插件安装

pnpm install html2canvas

二、具体实现

需求

点击“截图”实现对特定元素(id: target-element)截取

使用 html2canvas 插件通过 id 对元素截图

参数及解释

scale: 0.8, // 图片大小倍数
useCORS: true, // 解决跨域问题
allowTaint: true, // 允许画布内使用外部资源
backgroundColor: null, // 设置背景色为透明,默认为白色
logging: false, // 关闭html2canvas日志输出
imageSmoothingEnabled: false // 关闭抗锯齿

实现代码(Vue)

<template>
  <div >
    <div  @click="saveAsImage">截图</div>
    <img alt="Vue logo" src="./assets/logo.png" />
    <HelloWorld msg="Welcome to Your Vue.js App" />
  </div>
</template>
<script>
  import html2canvas from "html2canvas";
  import HelloWorld from "./components/HelloWorld.vue";

  export default {
    name: "App",
    components: {
      HelloWorld,
    },
    methods: {
      saveAsImage() {
        const element = document.querySelector("#target-element");
        const options = {
          scale: 0.8,
          useCORS: true,
          allowTaint: true,
          logging: false,
          imageSmoothingEnabled: false,
        };
        html2canvas(element, options).then(function (canvas) {
          const imgData = canvas.toDataURL("image/png");
          const link = document.createElement("a");
          link.download = "screenshot.png";
          link.href = imgData;
          link.click();
        });
      },
    },
  };
</script>

<style>
  #app {
    font-family: Avenir, Helvetica, Arial, sans-serif;
    -webkit-font-smoothing: antialiased;
    -moz-osx-font-smoothing: grayscale;
    text-align: center;
    color: #2c3e50;
    margin-top: 60px;
  }
  #btn {
    cursor: pointer;
    background-color: antiquewhite;
    color: #2c3e50;
    border-radius: 20%;
    width: 40px;
    margin: 0 auto;
    padding: 10px;
  }
</style>

实现效果

使用 html2canvas 插件通过 id 对元素截图