html2canvas,如果html中有image,需要转base64才能正常转换 image。本地调试可能存在跨域访问图片问题。由于图片服务器未开启跨域允许权限。
Uncaught DOMException: Failed to execute 'toDataURL' on 'HTMLCanvasElement': Tainted canvases may not be exported.
Access-Control-Allow-Origin: *
方式 1:
import axios from 'axios' const fetchImgFile = async (url: string) => { return await axios({ url: 'https://xxx.com.cn/xxx.png', responseType: "arraybuffer", }).then((response) => { // 将获取的二进制数据转换为Base64编码 const base64String = btoa( new Uint8Array(response.data).reduce( (data, byte) => data + String.fromCharCode(byte), "" ) ); return { src: "data:${image/jpeg};base64," + base64String, success: true, }; }).catch((error) => { console.error("Error fetching image:", error); return { success: false, src: "", }; }); }
方式2:
const fetchHandle = (imageUrl: string) => { // 使用fetch请求图片资源 fetch(imageUrl) .then(response => { // 确保请求成功 if (!response.ok) { throw new Error('Network response was not ok ' + response.statusText); } return response.blob(); // 将响应转换为Blob对象 }) .then(blob => { // 创建一个对象URL来代表Blob对象 const objectUrl = URL.createObjectURL(blob); // 创建一个新的Image元素并设置src属性为对象URL const img = document.createElement('img'); img.src = objectUrl; // 将图片添加到DOM中 document.body.appendChild(img); }) .catch(error => { console.error('There has been a problem with your fetch operation:', error); }); }
方式3:
const base64Handle = () => { // 创建一个Image对象 const img = new Image() img.crossOrigin = 'Anonymous' img.setAttribute('crossOrigin', 'Anonymous') img.crossOrigin = '*' // 设置图片加载完成后的回调函数 img.onload = function () { // 创建一个Canvas元素 const canvas = document.createElement('canvas') canvas.width = img.width canvas.height = img.height // 获取2D绘图上下文 const ctx = canvas.getContext('2d') // 在Canvas上绘制图片 ctx?.drawImage(img, 0, 0) // 将Canvas上的内容转换为Base64格式 const base64Data = canvas.toDataURL('image/png') // 打印Base64格式的图片数据 console(base64Data) } img.src = 'https://xxx.com/xxx.jpeg' }
标签:插件,const,img,image,base64,canvas,html2canvas,error,response From: https://www.cnblogs.com/swt-axios/p/18252646