使用html2canvas实现指定页面生成图片并下载

引入html2canvas插件,传入需要打印地方的dom,以及需要的相关配置(以下代码仅供参考)

<template>
    <div class="download">
        <el-button
              type="primary"
              icon="el-icon-download"
              @click="fileDownload"
            >{{content}}</el-button>
    </div>
</template>

<script>
import html2canvas from "html2canvas"; //引入html2canvas
export default {
    data() {
        return {
            downloadUrl:''
        }
    },
    props: {
        container: {
            default:()=>{}
        },
        content: {
            type: String,
            default:''
        },
        title: {
            type: String,
            default: ''
        }
    },
    methods: {
        // 生成快照
        convertToImage(container, options = {}) {
            // 设置放大倍数
            const scale = window.devicePixelRatio;
        
            // 传入节点原始宽高
            const width = container.offsetWidth;
            const height = container.offsetHeight;
        
            // html2canvas配置项
            const ops = {
                scale,
                width,
                height,
                useCORS: true,
                allowTaint: false,
                ...options
            };
        
           return html2canvas(container, ops).then(canvas => {
                // 返回图片的二进制数据
                return canvas.toDataURL("image/png");
            });
            // 调用函数,取到截图的二进制数据,对图片进行处理(保存本地、展示等)
        },
        /**
         * @desc: 下载到本地
         * @param {*} downloadUrl 
         */
        async fileDownload() {
            this.downloadUrl = await this.convertToImage(this.container)
            let aLink = document.createElement("a"); //生成a标签,通过a标签实现下载
            aLink.style.display = "none";
            aLink.href = this.downloadUrl;
            aLink.download = `${this.title}.png`;
            // 触发点击-然后移除
            document.body.appendChild(aLink);
            aLink.click();
            document.body.removeChild(aLink);
        }
    },

}
</script>

html2canvas 配置参数

html2canvas参数信息

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值