ts + vue 页面截图

背景:把当前页面某块功能生成图片

安装html2canvas

yarn add html2canvas
//HelloWorld.vue
<template>
<div id="html2canvas" ref="html2canvas">
    <button type="primary" @click="saveImage('html2canvas', 'test')">
      下载
    </button>
    <div>
      <p>内容</p>
      <p>内容</p>
      <p>内容</p>
      <p>内容</p>
      <p>内容</p>
      <p>内容</p>
      <p>内容</p>
      <p>内容</p>
    </div>
</div>
</template>
<script>
import { Component } from "vue-property-decorator";
import { screenShot } from "@/assets/js/screenshotUnit";
@Component
export default class extends screenShot {}
</script>
//screenshotUnit.ts
import { Vue } from "vue-property-decorator";
import html2canvas from "html2canvas";
export class screenShot extends Vue {
    //图片格式转换方法
    dataURLToBlob(dataurl: any): Record<string, any> {
        const arr = dataurl.split(",");
        const mime = arr[0].match(/:(.*?);/)[1];
        const bstr = atob(arr[1]);
        let n = bstr.length;
        const u8arr = new Uint8Array(n);
        while (n--) {
            u8arr[n] = bstr.charCodeAt(n);
        }
        return new Blob([u8arr], { type: mime });
    }
    //点击方法
    saveImage(divText: any, imgText: any): void {
        const canvasID = (this as any).$refs[divText];
        const a = document.createElement("a");
        html2canvas(canvasID).then((canvas: any) => {
            const dom = document.body.appendChild(canvas);
            dom.style.display = "none";
            a.style.display = "none";
            document.body.removeChild(dom);
            const blob: any = this.dataURLToBlob(dom.toDataURL("image/png"));
            a.setAttribute("href", URL.createObjectURL(blob));
            //这块是保存图片操作  可以设置保存的图片的信息
            a.setAttribute("download", imgText + ".png");
            document.body.appendChild(a);
            a.click();
            URL.revokeObjectURL(blob);
            document.body.removeChild(a);
        });
    }
}

啦啦啦,一个页面截图就写完了

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容