import { toJpeg, toPng } from "html-to-image"
/**
* @description 表示将 DOM 节点导出为图像时可配置的选项。
*/
export interface DomToImageOptions {
node: HTMLElement
imageType?: "jpeg" | "png" | undefined
extraOptions?: Exclude[1], undefined>
}
/**
* @description Convert a DOM node to an image (JPEG or PNG) and return the image as a data URL.
* The image type can be specified in the options, and additional options for the
* conversion can also be provided.
*/
export const domToImage = async (options: DomToImageOptions): Promise => {
const { node, imageType, extraOptions } = options
const preparedOptions = { cacheBust: true, ...extraOptions }
const toImage = imageType === "jpeg" ? toJpeg : toPng
const image = await toImage(node, preparedOptions)
return image
}
/**
* @description Convert a canvas element to a Blob object.
*/
export const canvasToBlob = async (canvas: HTMLCanvasElement): Promise => {
const blob = await new Promise((resolve) => {
canvas.toBlob((blob) => {
resolve(blob)
})
})
return blob
}