mccharts on HarmonyOS: Chart Engine Compatibility and Limits

0 阅读4分钟

The native option discussed here is @mcui/mccharts 3.0.0: a HarmonyOS chart component built on the Apache ECharts 6.1.0 option model and rendered through native GLES without a WebView. It is published on OHPM (ohpm install @mcui/mccharts@3.0.0).

A familiar chart option can make migration look deceptively simple: copy the axes and series into a HarmonyOS page, change the data, and expect the same result. Often the model carries across well. But a chart also depends on the host that measures text, presents graphics, receives gestures and exports images. Those parts need their own compatibility checks.

This article follows one small mccharts chart from option to screen, then looks at the places where a working browser example can need a different approach on HarmonyOS.

A mccharts demo chart with axes, labels and a legend

Start with the data and behavior you actually need

Imagine a store page with three days of order counts. Users tap a point to inspect it, and the page can replace the last value when new data arrives. Here's a complete V2 page:

import { McChartsV2 } from '@mcui/mccharts';
import type { ChartClick, Options } from '@mcui/mccharts';

function makeOrdersOption(last: number): Options {
  return {
    animation: false,
    tooltip: { trigger: 'item', renderMode: 'richText' },
    grid: { left: 48, right: 24, top: 35, bottom: 40 },
    xAxis: { type: 'category', data: ['Mon', 'Tue', 'Wed'] },
    yAxis: { type: 'value', name: 'Orders', min: 0 },
    dataZoom: [{ type: 'inside', start: 0, end: 100 }],
    series: [{
      id: 'orders', name: 'Orders', type: 'line',
      data: [12, 18, last]
    }]
  };
}

@Entry
@ComponentV2
struct CompatibilityPage {
  @Local private option: Options = makeOrdersOption(15);
  @Local private selected: string = 'Tap a data point';

  build() {
    Column({ space: 12 }) {
      McChartsV2({
        options: this.option,
        enableDataZoom: true,
        onChartClick: (event: ChartClick) => {
          this.selected = `${event.name}: ${event.value}`;
        }
      }).width('100%').height(320)
      Text(this.selected).width('100%')
      Button('Update Wednesday').onClick(() => {
        this.option = makeOrdersOption(21);
        this.selected = 'Data updated; select a point';
      })
    }.width('100%').padding(16)
  }
}

The axes, series and dataZoom model describe the chart. The component's enableDataZoom setting allows the corresponding inside gestures. The page supplies the height and owns the displayed selection. In a real app, use the clicked series and input index to find the matching business record; ChartClick.value is a display string, not a number to trust for calculations.

Which part is compatible?

Think in layers. The option names a model and its behavior: series, axes, data, animation, markers and actions. The native adapter turns the model's display output into frame data for the HarmonyOS host. The host supplies layout dimensions, text measurement, gestures and the native Surface.

A chart model crosses a native host boundary

The component creates an XComponent and reports size changes to its session. The runtime is created only when the session is attached, loaded and has an option and positive dimensions. Here is its actual guard:

if (!this.attached || this.controllerBindingFailed || !this.loaded || this.runtime || this.options === undefined || this.width <= 0 || this.height <= 0) { return; }

This makes a useful distinction: a field can exist in Options, while a particular visual effect, browser API or device combination still needs native support and testing. A successful type check says the code fits the declaration; it does not prove every configuration will render identically on every target.

HTML tooltips are a host boundary

An option containing renderMode: 'html' expects a browser DOM. The native runtime checks for it explicitly:

if (tooltip?.renderMode === 'html') {
  throw new Error('NATIVE_TOOLTIP_HTML_UNSUPPORTED: use renderMode richText or auto');
}

For simple text, richText and a synchronous formatter can be suitable. If the old tooltip contained a button, image or an asynchronously loaded table, an ArkUI detail panel driven by a chart event is usually a clearer migration. Merely changing renderMode while returning an HTML string does not recreate those controls.

The native path also rejects a formatter that returns a Promise. Fetch business data in the page or service, keep the necessary state there, and render the result in an appropriate native component. When copying an option that contains formatter functions, remember that JSON serialization removes functions; a JSON round-trip is not a general-purpose clone for such options.

New option reference, merge, and reset are three different ideas

The page example assigns a new Options object. The component observes options and resetKey:

@Monitor('options', 'resetKey')
onOptions(): void {
  const notMerge = this.appliedResetKey !== this.resetKey;
  if (this.session.updateOption(this.options, notMerge)) { this.appliedResetKey = this.resetKey; }
  this.interactionActive = this.session.isChartInteractionActive();
}

The new reference gets the change to the component boundary. It does not, by itself, say that every old series must be deleted. Ordinary updates merge. A page that removes a target series should choose an appropriate replacement strategy; a page switching to an entirely different store may choose a non-merge update or a changed resetKey.

If using McChartsController, keep one instance bound to one chart and keep business data in one authoritative place. A false result from setOption can mean work is pending, for example before layout or after a preceding failure. Repeatedly submitting the same command in a loop is not a readiness strategy. The pending queue keeps object references, so prepare a new object for the next change instead of mutating one already submitted.

Touch and event details need separate checks

A browser's hover and wheel behavior is not automatically the right interaction on a phone. The component routes ArkUI gestures into its session, and it uses the zoom and brush settings when deciding whether chart pan is enabled:

private interactionPanEnabled(): boolean {
  return this.enableDataZoom || (this.enableBrush && this.interactionActive);
}

Put the chart inside the actual Scroll or tab layout and try both chart gestures and page scrolling. If the user selects a marker, use onMarkerClick; a marker's dataIndex identifies its position in the marker list, not series.data. For raw chart events, the component's onChartEvent provides an { eventName, params } wrapper, while a controller onEvent callback receives raw parameters. Those differences matter when mapping a tap back to an order or device event.

Text, drawing and export have their own limits

In the default path, chart geometry and ArkUI text are presented by different layers. This supports readable labels, but arbitrary interleaving and clipping of text and shapes cannot be assumed to match a browser renderer. The raster-text path is available when the native Surface needs the text, including the current PNG export workflow.

For export, McChartsV2 must be mounted with rasterText: true and a usable Surface. The controller returns a PNG data URL asynchronously. The current implementation accepts pixelRatio: 1 and an empty or omitted excludeComponents; it captures the presented Surface instead of re-rendering an arbitrary larger image. Saving or sharing the result is application work.

An exported chart is not automatically a whole-page report. If the date filter, page title or table is outside the Surface, define how those elements should be composed into the final deliverable and verify the resulting image.

Large data changes the trade-off

Large scatter mode is useful for many uniformly styled points, but per-point styling, labels, emphasis and individual animation have limits in that mode. If a product needs a few highlighted alarms, consider a separate ordinary series and verify how selection behaves.

DataZoom narrows the visible window, but source data may still be parsed, filtered and laid out. Record total points, visible points, series count, chart size, update frequency and device before measuring. A browser timing or a host-side frame-generation test cannot establish HarmonyOS device FPS.

Likewise, the current native package must match the target device's ABI. A module configured for arm64-v8a is not proof that an x86 simulator can load the same native library, nor that every device with that ABI has been validated.

A practical compatibility check

Take the most demanding real screen, not just a gallery image. Verify the actual package version and source; then check first display, data update, filtered clicks, gestures within the page, departure and return. Add a target-device export check if the product needs images. Record the exact data and expected action for each step.

That process preserves the useful parts of a familiar option while giving the native host its due. Compatibility is most useful when it names the version, feature and environment, and when it explains what the application still needs to supply.