Skip to content

mxcad_2d API 文档 / tools / MxCanvas2Image

Class: MxCanvas2Image

tools.MxCanvas2Image

Canvas 转图片工具类,用于把浏览器中的 canvas 内容转换为图片并支持下载或生成图片元素。

Description

该类主要用于在前端页面中将 canvas 绘制结果导出为 PNG、JPEG、BMP、GIF 等常见图片格式,适用于截图、图表导出、图形分享和本地保存等场景。 它能完成:

  • 判断当前环境是否支持 canvas、toDataURL、ImageData 等能力;
  • 按指定宽高对 canvas 进行缩放;
  • 将 canvas 转成 DataURL 或图片对象;
  • 保存为图片文件到本地;
  • 对 BMP 类型做特殊编码以生成可下载的位图内容。

使用方式:

  1. 实例化 MxCanvas2Image;
  2. 传入 canvas 元素或元素 id;
  3. 调用 saveAsImage() 下载图片,或调用 convertToImage() 获取图片节点;
  4. 可通过 width、height、type 参数控制导出尺寸和格式;
  5. 若需导出 BMP,可按底层编码方式自动生成位图数据。

总结:MxCanvas2Image 是一个专门处理 canvas 导出与下载的工具类,适合在 Web 端把绘制内容快速转换为可保存的图片文件或可展示的 IMG 元素。

Example

ts
import { MxCanvas2Image } from "mxcad";

const canvas = document.getElementById("myCanvas") as HTMLCanvasElement;
const converter = new MxCanvas2Image(document);

// 直接下载为 PNG
converter.saveAsImage(canvas, 800, 600, "png");

// 转成图片节点并插入页面
const img = converter.convertToImage(canvas, 800, 600, "jpg");
document.body.appendChild(img);

// 转成 bmp 并下载
converter.saveAsImage(canvas, 1024, 768, "bmp");

Table of contents

Constructors

Methods

Constructors

constructor

new MxCanvas2Image(in_document?)

Parameters

NameTypeDefault value
in_documentanyundefined

Methods

convertToImage

convertToImage(canvas, width, height, type): undefined | HTMLImageElement

将当前 canvas 转换为图片元素。

Parameters

NameTypeDescription
canvasanycanvas 元素或其 id。
widthany导出图片的宽度,若未指定则使用 canvas 原始宽度。
heightany导出图片的高度,若未指定则使用 canvas 原始高度。
typeany导出图片的类型,可选值为 'png'、'jpeg'、'bmp'、'gif',默认值为 'png'。

Returns

undefined | HTMLImageElement

Description

该方法会根据传入的 canvas 元素或其 id,按指定的宽高和图片类型,将 canvas 内容转换为图片,并返回一个 HTMLImageElement 对象,可直接插入页面。


saveAsImage

saveAsImage(canvas, width, height, type): void

将当前 canvas 转换为图片并保存到本地。

Parameters

NameTypeDescription
canvasanycanvas 元素或其 id。
widthany导出图片的宽度,若未指定则使用 canvas 原始宽度。
heightany导出图片的高度,若未指定则使用 canvas 原始高度。
typeany导出图片的类型,可选值为 'png'、'jpeg'、'bmp'、'gif',默认值为 'png'。

Returns

void

Description

该方法会根据传入的 canvas 元素或其 id,按指定的宽高和图片类型,将 canvas 内容转换为图片,并触发浏览器下载。