import { fetchImage } from "./fetchImage" import { blobToImg } from "./blobToImg" import { isImageData } from "./isImageData" import { isBlob } from "./../../bit/funcs/isBlob" import { calcResizePostion } from "./calcResizePostion" /** * 把任何可绘制内容放到一个 canvas 里 * @param canvas 指定 canvas ,默认会创建一个新 canvas */ export async function toCanvas( inDrawable: string | Blob | HTMLImageElement | ImageData | ImageBitmap, canvas?: HTMLCanvasElement, options?: { useCanvasSize?: boolean clear?: boolean } ): Promise<{ canvas: HTMLCanvasElement; drawable: HTMLImageElement | ImageBitmap }> { if (!canvas) canvas = document.createElement("canvas") const ctx = canvas.getContext("2d") if (ctx === null) throw new Error("[fetchImage] canvas.getContext;") let drawable: HTMLImageElement | ImageData | ImageBitmap // 如果字符串就当作链接处理,转化为 Image if (typeof inDrawable === "string") { drawable = await fetchImage(inDrawable) } // 如果 Blob 就转化为 Image 处理 else if (isBlob(inDrawable)) { drawable = await blobToImg(inDrawable) } else { drawable = inDrawable } let x = 0 let y = 0 let w = drawable.width let h = drawable.height if (options?.useCanvasSize) { let xywh = calcResizePostion( { w: drawable.width, h: drawable.height }, { w: canvas.width, h: canvas.height }, "center" ) x = xywh.x y = xywh.y w = xywh.w h = xywh.h } else { // 设置 canvas 高度 canvas.width = drawable.width canvas.height = drawable.height w = canvas.width h = canvas.height } if (options?.clear) { ctx.clearRect(0, 0, canvas.width, canvas.height) } ctx.imageSmoothingEnabled = true ctx.imageSmoothingQuality = "high" if (isImageData(drawable)) { ctx.putImageData(drawable, x, y, 0, 0, w, h) } else { ctx.drawImage(drawable, x, y, w, h) } return { canvas, drawable } }