<template>
  <el-button v-if="showDownload" type="primary" @click="download">下载</el-button>
</template>
<script lang="ts">
import { defineComponent, PropType, ref, watch } from 'vue'
import html2canvas from 'html2canvas'
type Partial = {
  allowTaint: boolean
  backgroundColor: string
  canvas: HTMLCanvasElement
  foreignObjectRendering: boolean
  imageTimeout: number
  ignoreElements: (element: HTMLElement) => boolean
  logging: boolean
  onclone: () => void
  proxy: string
  removeContainer: boolean
  scale: number
  useCORS: boolean
  width: number
  height: number
  x: number
  y: number
  scrollX: number
  scrollY: number
  windowWidth: number
  windowHeight: number
}
export default defineComponent({
  name: 'SkH2C',
  props: {
    dom: HTMLElement,
    fileName: {
      type: String,
      default: 'h2c_image',
    },
    options: {
      type: Object as PropType<Partial>,
    },
    showDownload: {
      type: Boolean,
      default: true,
    },
  },
  emits: ['genImage'],
  setup (props, { emit }) {
    let url = ref('')
    const h2c = async () => {
      const canvas = await html2canvas(props.dom, props.options)
      url.value = canvas.toDataURL('image/png')
      emit('genImage', url)
    }
    watch(() => props.dom, () => {
      h2c()
    })
    const download = () => {
      const a = document.createElement('a')
      a.download = props.fileName
      a.href = url.value
      a.dispatchEvent(new MouseEvent('click'))
    }
    return {
      h2c,
      download,
    }
  },
})

</script>
<style>

</style>
