js使用html2canvas实现dom元素转图片并支持下载

65 阅读1分钟
以下VUE3为例

###### Install NPM

npm install --save html2canvas

###### Install Yarn

yarn add html2canvas

import html2canvas from 'html2canvas';


/**
 * dom元素转图片下载
 * @param {domRef} HTMLElement,通常用ref获取,如:dom.value
 * @param {info} 配置项
 * configObj: html2canvas 配置项 https://html2canvas.hertzen.com/configuration
 * imgType: 图片类型,默认 'image/png'
 * imgName: 图片名称,默认 'download.png'
 */
const downloadAsImage = async (domRef: HTMLElement, info = { configObj: {}, imgType: 'image/png', imgName: 'download.png' }) => {
  if (!domRef) return
  const defaultConfig = {
    scale: 1, // 提高分辨率(可选)
    useCORS: true // 允许跨域图片(如果有)
  }
  try {
    // 使用 html2canvas 转换节点为 canvas
    const canvas = await html2canvas(domRef, {
      ...defaultConfig,
      ...info.configObj
    })

    // 将 canvas 转换为 Data URL
    const imageUrl = canvas.toDataURL(info.imgType)

    // 创建下载链接
    const link = document.createElement('a')
    link.download = info.imgName // 设置文件名
    link.href = imageUrl
    link.click() // 触发下载
  } catch (error) {
    console.error('转换失败:', error)
  }
}

html部分

<script setup lang="ts">
  import { ref,onMounted } from 'vue'
  const domRef = ref()
  const url = ref()
  const getUrl = async ()=>{
     url.value = 'https://www.baidu.com'
  }
  
 onMounted(()=>{
   getUrl()
 })

</script>

<template>
    <div ref="domRef">
      // 动态获取的图片链接必须设置 crossorigin="anonymous",否则图片没法下载
      <img :src="url" alt="" crossorigin="anonymous" />
      <span>演示案例</span>
    </div>
   <div @click="downloadAsImage(domRef)">下载</div>
</template>