刘光辉
10 小时以前 0dfe84494048ce27ba8449831782128412d3eb13
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
<script lang="ts" setup>
  import * as echarts from 'echarts';
 
  defineOptions({ name: 'JnpfUniverFloatEchartVM' });
 
  const props = defineProps<PropsType>();
  interface PropsType {
    univerCreateMode: 'design' | 'preview' | 'print';
  }
  // 渲染
  function render(domId: string, option: echarts.EChartsOption, width: number, height: number) {
    // 创建一个临时容器
    const tempContainer = document.createElement('div');
    tempContainer.style.width = `${width}px`;
    tempContainer.style.height = `${height}px`;
    tempContainer.style.position = 'absolute';
    tempContainer.style.visibility = 'hidden'; // 避免影响页面视觉
    document.body.append(tempContainer);
 
    let chartToImageUrl: null | string = null;
 
    if (props.univerCreateMode === 'preview') {
      try {
        // 初始化 ECharts 实例
        const tempChartInstance = echarts.init(tempContainer);
 
        // 配置图表选项
        const updateOption = {
          ...option,
          animation: false, // 禁用动画以提高生成效率
        };
 
        const { color, ...restOption } = updateOption;
 
        // 设置图表选项
        tempChartInstance.setOption(restOption);
 
        // 获取图表的 Base64 图片 URL
        chartToImageUrl = tempChartInstance.getDataURL({
          backgroundColor: '#f9f9f9',
          type: 'jpeg',
        });
 
        // 销毁图表实例
        tempChartInstance.dispose();
      } catch (error) {
        console.error('图表生成失败:', error);
      } finally {
        // 移除临时容器
        tempContainer.remove();
      }
 
      return {
        domId,
        source: chartToImageUrl,
      };
    }
  }
 
  defineExpose({
    render,
  });
</script>
 
<template>
  <div style="display: none; width: 0; height: 0"></div>
</template>