The examples in this article use @mcui/mccharts 3.0.0, a native chart component for ArkUI on HarmonyOS. It reuses the Apache ECharts 6.1.0 option model, draws through a native GLES path, and needs no WebView. The package is published on OHPM: ohpm install @mcui/mccharts@3.0.0.
A user taps “Export” and expects a picture. Underneath, the chart first needs a live Surface containing the visible frame, then that Surface must be captured and encoded. The returned PNG data is still not a photo-album entry or a share sheet; the application decides what to do with it next.
This article follows the McChartsV2 export path and uses a small page that previews the result. The same page can later hand the data to the application's own file or sharing flow.
A page with an export button
import { McChartsV2, McChartsController } from '@mcui/mccharts';
import type { Options } from '@mcui/mccharts';
@Entry
@ComponentV2
struct ChartExportPage {
private controller: McChartsController = new McChartsController();
private option: Options = {
animation: false,
xAxis: { type: 'category', data: ['Mon', 'Tue', 'Wed'] },
yAxis: { type: 'value', min: 0, name: 'Orders' },
series: [{ id: 'orders', type: 'bar', data: [12, 18, 15] }]
};
@Local private imageURI: string = '';
@Local private status: string = 'Tap Export after the chart appears';
@Local private busy: boolean = false;
private async exportChart(): Promise<void> {
if (this.busy) return;
this.busy = true;
this.status = 'Creating PNG';
try {
this.imageURI = await this.controller.getDataURL({
type: 'png', pixelRatio: 1, excludeComponents: [],
backgroundColor: '#FFFFFF'
});
this.status = 'PNG ready for preview';
} catch (error) {
this.status = `Export failed: ${String(error)}`;
} finally {
this.busy = false;
}
}
build() {
Scroll() {
Column({ space: 12 }) {
McChartsV2({
options: this.option,
controller: this.controller,
rasterText: true
}).width('100%').height(320)
Button('Export').enabled(!this.busy).onClick(() => this.exportChart())
Text(this.status).width('100%')
if (this.imageURI.length > 0) {
Image(this.imageURI).width('100%').objectFit(ImageFit.Contain)
}
}.width('100%').padding(16)
}
}
}
The component and controller belong to the same chart. rasterText: true enables the text path needed by the current Surface capture. The button prevents repeated concurrent exports and reports a failure instead of treating an empty result as a successful image. If the page can disappear during export, the production page also needs to decide whether a late result should still update its state.
The returned value is Promise<string> containing a PNG data URL. Showing it with Image is a preview. Saving a file, adding it to an album or opening system sharing requires additional application code and the relevant platform flow.
What does the session check?
Before capture, the session checks attachment, disposal, runtime initialization and failure state. It also checks the text mode:
if (!this.attached || this.disposed || !this.runtime || this.failed || !this.modelInitialized) {
throw new Error('ECharts instance is not ready.');
}
if (!this.rasterText) { throw new Error('NATIVE_EXPORT_RASTER_TEXT_REQUIRED'); }
That internal error string is part of the actual source. The session then resolves a Surface ID, checks that capture is available and validates options. If a Surface is not ready, keep the concrete error and inspect the component's mounting, layout and lifecycle. Do not invent an onReady component property or use a fixed delay as proof that a Surface has a completed frame.
From Surface to PNG bytes
The capture implementation obtains a PixelMap using the Surface ID. If a supported solid background was requested, it can create a composited PixelMap before encoding. The core encoding lines are:
surface = await image.createPixelMapFromSurface(surfaceId);
// Optional background compositing selects the source PixelMap.
packer = image.createImagePacker();
const encoded = await packer.packToData(source, { format: 'image/png', quality: 100 });
const base64 = new util.Base64Helper().encodeToStringSync(new Uint8Array(encoded));
return `data:image/png;base64,${base64}`;
This is an explanatory excerpt from the longer capture function. The actual function checks the result, handles optional background composition and releases the Surface PixelMap, composed PixelMap and ImagePacker in finally. That cleanup matters when users export repeatedly.
The implementation places a 16 MiB limit on the encoded PNG bytes before Base64 conversion. Base64 creates a larger string representation, and a preview can keep that string in memory. A page that generates many large images should manage concurrency and release references it no longer needs.
Options that look familiar may have different limits
For this native path, use PNG, pixelRatio: 1 and an empty or omitted excludeComponents. The result captures the currently presented native Surface; it is not a separate high-resolution re-render of a display list. A non-empty exclusion list or a different pixel ratio is rejected by the current implementation.
If a toolbar is visible in the captured chart, plan for it to appear in the snapshot. If the product needs a clean report without controls, design and validate an export-specific chart or layout; passing an unsupported exclusion option will not remove it.
Supported background inputs include the documented hexadecimal forms and a few named values. An unsupported background causes an explicit error. A browser playground's Canvas image is a separate rendering path and cannot establish what the HarmonyOS Surface snapshot contains.
When export fails, locate the layer
First confirm that the chart is mounted with non-zero size and that its initial option is valid. Next check rasterText, Surface availability, the requested PNG parameters and the exact error. If a valid data URL is returned but the system share fails, investigate the application's sharing step rather than repeatedly changing the chart option.
Test the image itself: axis labels, title, legend, long names, background and any visible controls. For a whole-page report with a header and table outside the chart, define a separate page-level capture or composition requirement. A chart Surface snapshot only answers the chart export part of that request.