Skip to content

工具函数

TaroViz 提供了一系列实用工具函数,用于简化图表开发和管理。

1. 主题管理

registerTheme

注册自定义主题。

导入

typescript
import { registerTheme } from '@agions/taroviz';

类型定义

typescript
function registerTheme(name: string, theme: object): void;

参数

参数名类型描述
namestring主题名称
themeobject主题配置对象

示例

typescript
registerTheme('custom-theme', {
  color: ['#5470c6', '#91cc75', '#fac858', '#ee6666', '#73c0de'],
  backgroundColor: '#f5f5f5',
  textStyle: {
    color: '#333',
  },
  title: {
    textStyle: {
      color: '#222',
      fontWeight: 'bold',
    },
  },
});

getTheme

获取指定主题。

导入

typescript
import { getTheme } from '@agions/taroviz';

类型定义

typescript
function getTheme(name: string): object | undefined;

参数

参数名类型描述
namestring主题名称

返回值

类型描述
object主题配置对象
undefined如果主题不存在

示例

typescript
const theme = getTheme('default');
console.log('默认主题:', theme);

getAllThemes

获取所有注册的主题。

导入

typescript
import { getAllThemes } from '@agions/taroviz';

类型定义

typescript
function getAllThemes(): string[];

返回值

类型描述
string[]主题名称数组

示例

typescript
const themes = getAllThemes();
console.log('所有主题:', themes);

2. 平台适配

registerAdapter

注册自定义平台适配器。

导入

typescript
import { registerAdapter } from '@agions/taroviz';

类型定义

typescript
interface Adapter {
  init(options: any): any;
  render(chart: any, option: any): void;
  resize(chart: any, width: number, height: number): void;
  destroy(chart: any): void;
  getInstance(chart: any): any;
  setOption(chart: any, option: any, notMerge?: boolean, lazyUpdate?: boolean): void;
  getOption(chart: any): any;
  on(chart: any, eventName: string, handler: (params: any) => void): void;
  off(chart: any, eventName: string, handler: (params: any) => void): void;
}

function registerAdapter(name: string, adapter: typeof Adapter | Adapter): void;

参数

参数名类型描述
namestring适配器名称
adaptertypeof Adapter适配器类或实例

示例

typescript
class CustomAdapter {
  init(options: any) {
    // 初始化逻辑
    return {};
  }

  render(chart: any, option: any) {
    // 渲染逻辑
  }

  resize(chart: any, width: number, height: number) {
    // 调整大小逻辑
  }

  destroy(chart: any) {
    // 销毁逻辑
  }

  getInstance(chart: any) {
    // 获取实例逻辑
    return chart;
  }

  setOption(chart: any, option: any, notMerge?: boolean, lazyUpdate?: boolean) {
    // 设置配置逻辑
  }

  getOption(chart: any) {
    // 获取配置逻辑
    return {};
  }

  on(chart: any, eventName: string, handler: (params: any) => void) {
    // 绑定事件逻辑
  }

  off(chart: any, eventName: string, handler: (params: any) => void) {
    // 解绑事件逻辑
  }
}

registerAdapter('custom', CustomAdapter);

getAdapter

获取指定平台的适配器。

导入

typescript
import { getAdapter } from '@agions/taroviz';

类型定义

typescript
function getAdapter(name: string): Adapter | undefined;

参数

参数名类型描述
namestring适配器名称

返回值

类型描述
Adapter适配器实例
undefined如果适配器不存在

示例

typescript
const adapter = getAdapter('weapp');
console.log('微信小程序适配器:', adapter);

detectPlatform

检测当前运行平台。

导入

typescript
import { detectPlatform } from '@agions/taroviz';

类型定义

typescript
function detectPlatform(): string;

返回值

类型描述
string当前平台名称

示例

typescript
const platform = detectPlatform();
console.log('当前平台:', platform);

3. 图表实例管理

registerChart

注册图表实例。

导入

typescript
import { registerChart } from '@agions/taroviz';

类型定义

typescript
function registerChart(chartId: string, chartInstance: any): void;

参数

参数名类型描述
chartIdstring图表ID
chartInstanceany图表实例

示例

typescript
const chart = echarts.init(dom);
registerChart('chart-1', chart);

getChart

获取图表实例。

导入

typescript
import { getChart } from '@agions/taroviz';

类型定义

typescript
function getChart(chartId: string): any | undefined;

参数

参数名类型描述
chartIdstring图表ID

返回值

类型描述
any图表实例
undefined如果图表不存在

示例

typescript
const chart = getChart('chart-1');
if (chart) {
  chart.resize();
}

removeChart

移除图表实例。

导入

typescript
import { removeChart } from '@agions/taroviz';

类型定义

typescript
function removeChart(chartId: string): void;

参数

参数名类型描述
chartIdstring图表ID

示例

typescript
removeChart('chart-1');

getAllCharts

获取所有注册的图表实例。

导入

typescript
import { getAllCharts } from '@agions/taroviz';

类型定义

typescript
function getAllCharts(): Record<string, any>;

返回值

类型描述
Record<string, any>图表实例映射对象

示例

typescript
const charts = getAllCharts();
console.log('所有图表实例:', charts);

4. 配置生成

generateChartConfig

生成图表配置。

导入

typescript
import { generateChartConfig } from '@agions/taroviz';

类型定义

typescript
interface ConfigGeneratorOptions {
  /**
   * 图表类型
   */
  type: string;
  /**
   * 标题
   */
  title?: string;
  /**
   * 副标题
   */
  subtitle?: string;
  /**
   * 数据
   */
  data?: any;
  /**
   * X轴数据
   */
  xAxisData?: any[];
  /**
   * Y轴数据
   */
  yAxisData?: any[];
  /**
   * 系列配置
   */
  seriesConfig?: any;
  /**
   * 主题
   */
  theme?: string | object;
  /**
   * 是否响应式
   */
  responsive?: boolean;
  /**
   * 其他配置
   */
  [key: string]: any;
}

function generateChartConfig(options: ConfigGeneratorOptions): any;

参数

参数名类型描述
optionsobject配置生成选项

返回值

类型描述
object图表配置对象

示例

typescript
const config = generateChartConfig({
  type: 'line',
  title: '销售趋势',
  data: [120, 200, 150, 80, 70, 110, 130],
  xAxisData: ['1月', '2月', '3月', '4月', '5月', '6月', '7月'],
});
console.log('生成的配置:', config);

5. 代码生成

generateCodeExample

生成代码示例。

导入

typescript
import { generateCodeExample } from '@agions/taroviz';

类型定义

typescript
interface CodeGeneratorOptions {
  /**
   * 框架类型
   */
  framework: 'react' | 'vue' | 'vanilla';
  /**
   * 图表类型
   */
  chartType: string;
  /**
   * 图表配置
   */
  option: any;
  /**
   * 是否包含类型定义
   */
  includeTypes?: boolean;
}

function generateCodeExample(options: CodeGeneratorOptions): string;

参数

参数名类型描述
optionsobject代码生成选项

返回值

类型描述
string代码示例文本

示例

typescript
const code = generateCodeExample({
  framework: 'react',
  chartType: 'line',
  option: {
    title: { text: '示例' },
    xAxis: { type: 'category', data: ['A', 'B', 'C'] },
    yAxis: { type: 'value' },
    series: [{ data: [1, 2, 3], type: 'line' }],
  },
  includeTypes: true,
});
console.log(code);

6. 性能分析

PerformanceAnalyzer

性能分析工具类,用于监控和分析图表性能。

导入

typescript
import { PerformanceAnalyzer } from '@agions/taroviz';

类型定义

typescript
class PerformanceAnalyzer {
  /**
   * 开始监控
   */
  start(): void;
  /**
   * 停止监控
   */
  stop(): void;
  /**
   * 获取性能报告
   */
  getReport(): PerformanceReport;
  /**
   * 重置统计数据
   */
  reset(): void;
}

interface PerformanceReport {
  fps: number;
  renderTime: number;
  memoryUsage: number;
  dataProcessTime: number;
  initTime: number;
  samples: number;
}

示例

typescript
import { PerformanceAnalyzer } from '@agions/taroviz';

const analyzer = new PerformanceAnalyzer();
analyzer.start();

// ... 图表操作 ...

const report = analyzer.getReport();
console.log('帧率:', report.fps, 'FPS');
console.log('渲染时间:', report.renderTime, 'ms');

analyzer.stop();

7. 调试工具

DebugLogger

调试日志工具,用于开发阶段输出调试信息。

导入

typescript
import { DebugLogger } from '@agions/taroviz';

类型定义

typescript
class DebugLogger {
  /**
   * 设置日志级别
   */
  setLevel(level: 'debug' | 'info' | 'warn' | 'error'): void;
  /**
   * 输出调试日志
   */
  debug(message: string, data?: any): void;
  /**
   * 输出信息日志
   */
  info(message: string, data?: any): void;
  /**
   * 输出警告日志
   */
  warn(message: string, data?: any): void;
  /**
   * 输出错误日志
   */
  error(message: string, data?: any): void;
}

示例

typescript
import { DebugLogger } from '@agions/taroviz';

const logger = new DebugLogger();
logger.setLevel('debug');

logger.debug('图表初始化', { chartId: 'chart-1' });
logger.info('渲染完成', { renderTime: 45 });

8. 导出工具

exportToPNG

导出图表为 PNG 图片。

导入

typescript
import { exportToPNG } from '@agions/taroviz';

类型定义

typescript
function exportToPNG(
  chartInstance: any,
  filename?: string,
  pixelRatio?: number
): Promise<string>;

参数

参数名类型描述
chartInstanceany图表实例
filenamestring文件名(可选)
pixelRationumber分辨率(可选)

返回值

类型描述
Promise图片数据 URL

示例

typescript
const imageUrl = await exportToPNG(chartInstance, 'my-chart', 2);

exportToSVG

导出图表为 SVG 矢量图。

导入

typescript
import { exportToSVG } from '@agions/taroviz';

类型定义

typescript
function exportToSVG(chartInstance: any, filename?: string): Promise<string>;

参数

参数名类型描述
chartInstanceany图表实例
filenamestring文件名(可选)

返回值

类型描述
PromiseSVG 内容

示例

typescript
const svgContent = await exportToSVG(chartInstance, 'my-chart');

exportToPDF

导出图表为 PDF 文档。

导入

typescript
import { exportToPDF } from '@agions/taroviz';

类型定义

typescript
function exportToPDF(chartInstance: any, filename?: string): Promise<Blob>;

参数

参数名类型描述
chartInstanceany图表实例
filenamestring文件名(可选)

返回值

类型描述
BlobPDF 文件

示例

typescript
const pdfBlob = await exportToPDF(chartInstance, 'my-chart.pdf');

Released under the MIT License.