/** * @file DOM 元素或 DOM 事件相关的 utils */ // re-use canvas object for better performance let canvas: HTMLCanvasElement | null = null /** * 计算一段文本用指定字体渲染后的长度 (width) * * @param text - 文本 * @param font - 字体, for example "bold 14px 'Helvetica Neue', 'Roboto', sans-serif" * @returns 渲染后的 width */ export function getTextWidth(text: string, font: string) { canvas = canvas ?? document.createElement('canvas') const context = canvas.getContext('2d') if (!context) return 0 context.font = font const metrics = context.measureText(text) return metrics.width } /** * 将指定 html 元素转换为 canvas. * 内置了一些预处理逻辑: * 1. 目标元素内带有 data-html-to-canvas-remove 属性的元素都会在转换前被移除 * * @param el - 目标元素 * @param scale - 放大倍数 * @param preprocess - 转换前的预处理, 一般用于对样式进行调整 (在 clone 的元素中进行, 不影响原元素) * * @returns Promise of canvas element */ export function htmlToCanvas({ el, preprocess, scale = 1, }: { el: HTMLElement preprocess?: (el: HTMLElement) => HTMLElement scale?: number }): Promise { const originWidth = el.offsetWidth // 为了在调整内容和样式时不影响原元素,需要 clone el let cloneEl = el.cloneNode(true) as HTMLElement cloneEl.style.cssText += `;position: absolute;top: 0;left: 0;z-index: -999; width:${originWidth}px;` if (preprocess) cloneEl = preprocess(cloneEl) // 删除带有属性 data-html-to-canvas-remove 的元素 const delElement = cloneEl.querySelectorAll('[data-html-to-canvas-remove]') delElement.forEach(element => { element.parentNode?.removeChild(element) }) document.body.appendChild(cloneEl) return import('html2canvas').then( ({ default: html2canvas }) => new Promise(resolve => { setTimeout(() => { html2canvas(cloneEl, { scale }).then(cvs => { resolve(cvs) setTimeout(() => { document.body.removeChild(cloneEl) }) }) // 确保 el 渲染完成 }, 400) }), ) }