import { hexToRgb } from '../theme'; // 非递归、深度优先遍历 // const DFSDomTraversal = (root) => { // if (!root) return; // const arr = []; // const queue = [root]; // let node = queue.shift(); // while (node) { // arr.push(node); // if (node.children.length) { // for (let i = node.children.length - 1; i >= 0; i--) { // queue.unshift(node.children[i]); // } // } // node = queue.shift(); // } // return arr; // }; // // 凡是要复制的样式,都写在这 // const CSSRules = ['color', 'border', 'width', 'margin-right']; // const copyStyle = (element) => { // const styles = getComputedStyle(element); // CSSRules.forEach((rule) => { // element.style.setProperty(rule, styles.getPropertyValue(rule)); // }); // }; // const img2base64 = (element) => { // return new Promise((resolve, reject) => { // const img = new Image(); // // 处理 canvas 受污染的情况 // img.crossOrigin = 'anonymous'; // img.onerror = reject; // img.onload = function () { // const canvas = document.createElement('canvas'); // const ctx = canvas.getContext('2d'); // canvas.width = this.naturalWidth; // canvas.height = this.naturalHeight; // ctx.drawImage(this, 0, 0); // resolve(canvas.toDataURL()); // }; // img.src = element.src; // }); // }; // export const dom2base64 = async (chart, root, callback) => { // // DFSDomTraversal(root).forEach(copyStyle); // // const imgElements = [...root.querySelectorAll('img')]; // // const base64Result = await Promise.all(imgElements.map(img2base64)); // // const width = root.offsetWidth; // // const height = root.offsetHeight; // // let XHTML = new XMLSerializer().serializeToString(root); // // imgElements.forEach((element, index) => { // // XHTML = XHTML.replace(element.src, base64Result[index]); // // }); // // const xh = // // '

fdsfd

dfdsfdfd

'; // // const SVGDomElement = ` // // // // ${xh} // // `; // const SVGDomElement = ` // // //
// ${root} //
//
//
`; // console.log(XMLSerializer); // const img = chart.canvas.element.createImage(); // // const img = new Image(); // img.onload = function () { // callback(img); // console.log(img); // }; // img.src = `data:image/svg+xml,${SVGDomElement}`; // }; /** * 对html片段进行处理 * 转换css颜色 十六进制为rgb foreignObject里面的代码片段遇到十六进制就报错了 * @param htmlSnip * @returns */ const processHtmlSnip = (htmlSnip: string) => { if (!htmlSnip) return; return htmlSnip.replace(/#[0-9a-fA-F]+/g, (hex) => hexToRgb(hex)).replace(/[\r\n]+/g, ''); }; export const domToString = (node) => { if (typeof node === 'string') return node; let tmpNode = document.createElement('div'); if (Array.isArray(node)) { node.forEach((n) => tmpNode.appendChild(n)); } else { tmpNode.appendChild(node); } const str = tmpNode.innerHTML; tmpNode = null; return str; }; export const htmlSnipToSvg: (htmlSnip: string, width: number) => string = (htmlSnip, width) => { const style = ` border-radius: 2px; padding: 5px; background: white; box-shadow: 0 0 4px rgba(0, 0, 0, 0.3);`; const svg = `
${htmlSnip}
`; const svgPrefix = 'data:image/svg+xml,'; return svgPrefix + processHtmlSnip(svg); };