<template>
  <div class="guns-body guns-body-card">
    <a-card title="页面转换成图片" :bordered="false">
      <a-button @click="generateImage">点击转换</a-button>
      <div id="imageDom">
        <img src="@/assets/logo.png" alt="" />
        <div>转成图片</div>
      </div>
    </a-card>
    <a-card title="页面转换成图片-预览" :bordered="false">
      <img :src="gengerPic" alt="" />
    </a-card>
  </div>
</template>

<script setup>
import { ref } from 'vue';
import html2canvas from 'html2canvas';
import { FileApi } from '@/views/system/backend/file/api/FileApi';

const gengerPic = ref('');

const fileId = ref('');

//div内容生成图片
const generateImage = () => {
  const element = document.getElementById('imageDom');
  html2canvas(element, {
    useCORS: true // 添加这个选项以解决跨域问题
  }).then(canvas => {
    // 将canvas转换为图片数据URL
    const image = canvas.toDataURL('image/png');
    gengerPic.value = image;
  });
};

//div内容生成图片 --- 存储到后台
const generateImage2 = () => {
  const element = document.getElementById('imageDom');
  html2canvas(element, {
    useCORS: true // 添加这个选项以解决跨域问题
  }).then(canvas => {
    // 将canvas转换为图片数据URL
    const image = canvas.toDataURL('image/png');
    convertImageToBlob(image, blob => {
      const formData = new FormData();
      formData.append('file', blob, 'form.png');
      FileApi.commonUpload('N', formData).then(res => {
        fileId.value = res.data.fileId;
      });
    });
  });
};

// 使用fetch API将图片数据URL转换为Blob对象
const convertImageToBlob = (image, callback) => {
  fetch(image)
    .then(res => res.blob())
    .then(blob => callback(blob));
};
</script>

<style></style>
