2025-07-29 19:18:58 +08:00
|
|
|
import { base64ToBlob, uuid } from "./comm";
|
2025-07-29 13:26:31 +08:00
|
|
|
|
|
|
|
|
/**
|
|
|
|
|
* 将canvas转换为png图片
|
|
|
|
|
* @param options 转换参数
|
|
|
|
|
* @returns 图片路径
|
|
|
|
|
*/
|
2025-08-02 17:17:13 +08:00
|
|
|
export function canvasToPng(canvasRef: UniElement): Promise<string> {
|
2025-07-29 13:26:31 +08:00
|
|
|
return new Promise((resolve) => {
|
|
|
|
|
// #ifdef APP
|
2025-08-02 17:17:13 +08:00
|
|
|
canvasRef.parentElement!.takeSnapshot({
|
2025-07-29 13:26:31 +08:00
|
|
|
success(res) {
|
|
|
|
|
resolve(res.tempFilePath);
|
|
|
|
|
},
|
|
|
|
|
fail(err) {
|
|
|
|
|
console.error(err);
|
|
|
|
|
resolve("");
|
|
|
|
|
}
|
|
|
|
|
});
|
|
|
|
|
// #endif
|
|
|
|
|
|
|
|
|
|
// #ifdef H5
|
|
|
|
|
const url = URL.createObjectURL(
|
|
|
|
|
base64ToBlob(
|
2025-08-02 17:17:13 +08:00
|
|
|
(canvasRef as unknown as HTMLCanvasElement)?.toDataURL("image/png", 1) ?? ""
|
2025-07-29 13:26:31 +08:00
|
|
|
)
|
|
|
|
|
);
|
|
|
|
|
|
|
|
|
|
resolve(url);
|
|
|
|
|
// #endif
|
|
|
|
|
|
|
|
|
|
// #ifdef MP
|
|
|
|
|
uni.createCanvasContextAsync({
|
2025-08-02 17:17:13 +08:00
|
|
|
id: canvasRef.id,
|
|
|
|
|
component: canvasRef.$vm,
|
2025-07-29 13:26:31 +08:00
|
|
|
success(context) {
|
|
|
|
|
// 获取2D绘图上下文
|
|
|
|
|
const ctx = context.getContext("2d")!;
|
2025-08-02 17:17:13 +08:00
|
|
|
|
|
|
|
|
// 获取canvas对象
|
2025-07-29 13:26:31 +08:00
|
|
|
const canvas = ctx.canvas;
|
|
|
|
|
|
|
|
|
|
// 将canvas转换为base64格式的PNG图片数据
|
|
|
|
|
const data = canvas.toDataURL("image/png", 1);
|
|
|
|
|
|
|
|
|
|
// 获取文件系统管理器
|
|
|
|
|
const fileMg = uni.getFileSystemManager();
|
2025-08-02 17:17:13 +08:00
|
|
|
|
2025-07-29 13:26:31 +08:00
|
|
|
// 生成临时文件路径
|
|
|
|
|
// @ts-ignore
|
|
|
|
|
const filepath = `${wx.env.USER_DATA_PATH}/${uuid()}.png`;
|
2025-08-02 17:17:13 +08:00
|
|
|
|
2025-07-29 13:26:31 +08:00
|
|
|
// 将base64数据写入文件
|
|
|
|
|
fileMg.writeFile({
|
|
|
|
|
filePath: filepath,
|
2025-08-02 17:17:13 +08:00
|
|
|
data: data.split(",")[1],
|
2025-07-29 13:26:31 +08:00
|
|
|
encoding: "base64",
|
|
|
|
|
success() {
|
|
|
|
|
resolve(filepath);
|
|
|
|
|
},
|
2025-08-02 17:17:13 +08:00
|
|
|
fail(err) {
|
|
|
|
|
console.error(err);
|
2025-07-29 13:26:31 +08:00
|
|
|
resolve("");
|
|
|
|
|
}
|
|
|
|
|
});
|
|
|
|
|
},
|
|
|
|
|
fail(err) {
|
|
|
|
|
console.error(err);
|
|
|
|
|
resolve("");
|
|
|
|
|
}
|
|
|
|
|
});
|
|
|
|
|
// #endif
|
|
|
|
|
});
|
|
|
|
|
}
|