html2canvas 导出超长页面

1. 安装 html2canvas

首先,你需要安装 html2canvas

npm install html2canvas

2. 创建 Vue 组件

接下来,创建一个 Vue 组件,并在其中使用 html2canvas 来导出页面为图片。

<template>
  <div ref="contentRef">
    <!-- 你的超长页面内容 -->
  </div>
  <button @click="exportToImage">导出为图片</button>
</template>

<script setup>
import { ref } from 'vue';
import html2canvas from 'html2canvas';

const contentRef = ref(null);

const exportToImage = async () => {
  try {
    const element = contentRef.value;
    if (!element) return;

    // 配置选项(关键参数)
    const options = {
      scale: 2, // 提升清晰度
      useCORS: true, // 允许跨域图片
      allowTaint: true, // 处理tainted canvas问题
      scrollY: -window.scrollY, // 消除滚动偏移
      windowHeight: document.documentElement.scrollHeight, // 完整页面高度
    };

    // 生成Canvas
    const canvas = await html2canvas(element, options);

    // 转换为图片并下载
    const imgData = canvas.toDataURL('image/png');
    const link = document.createElement('a');
    link.download = 'page-screenshot.png';
    link.href = imgData;
    link.click();
  } catch (error) {
    console.error('导出失败:', error);
  }
};
</script>

这样就可以实现页面直接导出为图片的功能

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值