import html2canvas from 'html2canvas';
import {baseURL,apiURL,cffpURL,sfpUrl,imgUrl,scrmUrl} from "../environments/environment";

/**
 * 将DOM元素转换为图片
 * @param {HTMLElement} element DOM元素
 * @param {Object} options html2canvas配置选项
 * @returns {Promise<string>} 返回图片的base64数据
 */
export const elementToImage = async (element, options = {}) => {
  try {
    // 默认配置
    const defaultOptions = {
      backgroundColor: null, // 透明背景
      scale: 2, // 提高缩放以获得更清晰的图片
      useCORS: true, // 允许跨域图片
      allowTaint: false, // 允许污染图片
      logging: false, // 关闭日志，
	  delay: 10000
    };
    const canvas = await html2canvas(element, { ...defaultOptions, ...options });
    return canvas.toDataURL('image/png');
  } catch (error) {
    console.error('生成图片失败:', error);
    throw error;
  }
};
export function  convertImageToBase64Frontend  (url) {
  return new Promise((resolve, reject) => {
    const img = new Image();
    img.crossOrigin = 'anonymous'; // 处理跨域问题
    img.src = url;
    console.log('img',img);
    img.onload = () =>{
      const canvas = document.createElement('canvas');
      const ctx = canvas.getContext('2d');
      canvas.height = img.naturalHeight;
      canvas.width = img.naturalWidth;
      ctx.drawImage(img, 0, 0);
      
      try {
        const dataURL = canvas.toDataURL('image/png');
        resolve(dataURL);
      } catch (e) {
        reject(e);
      }
    };
    
    img.onerror = function() {
      reject(new Error('图片加载失败'));
    };
  });
}