VChart中轴标签如何使用Html渲染?

156 阅读1分钟

坐标轴的标签,如何使用自定义html 渲染,另外可以实现自定义的跳转链接吗?

解决方案

VChart的轴标签是支持使用html绝对定位进行展示的,要实现该功能:

  • 第一步: VChart需要通过enableHtmlAttribute: true打开相关插件
const vchart = new VChart(spec, { dom: CONTAINER_ID, enableHtmlAttribute: true });
vchart.renderSync();
  • 第二步:在轴标签配置的时候,通过formatMethod返回html类型的标签
  • 第三步:通过<a>标签实现自定义的url跳转,并设置pointerEvents: 'auto'打开标签的鼠标事件
axes: [
    {
      orient: 'bottom',
      sampling: false,
      label: {
        style: {
          forceBoundsWidth: 40
        },
        formatMethod: (label, a) => {
          return {
            type: 'html',
            text: {
              pointerEvents: 'auto',
              id: `x-label-${label}`,
              style: {
                width: '40px',
                overflow: 'hidden'
              },
              dom: `<a href="https://visactor.com/vchart/demo/line-chart/dash-line">${label}</a>`
            }
          };
        }
      }
    }
  ],

代码示例

const spec = {
  type: 'line',
  data: {
    values: [
      {
        x: '1st',
        y: 0.012
      },
      {
        x: '2nd',
        y: -0.01
      },
      {
        x: '3rd',
        y: 0.005
      },
      {
        x: '4th',
        y: 0.007
      },
      {
        x: '5th',
        y: 0.01
      },
      {
        x: '6th',
        y: 0.017
      },
      {
        x: '7th',
        y: 0.022
      },
      {
        x: '8th (prediction)',
        y: 0.033,
        latest: true
      }
    ]
  },
  xField: 'x',
  yField: 'y',
  axes: [
    {
      orient: 'bottom',
      sampling: false,
      label: {
        style: {
          forceBoundsWidth: 40
        },
        formatMethod: (label, a) => {
          return {
            type: 'html',
            text: {
              pointerEvents: 'auto',
              id: `x-label-${label}`,
              style: {
                width: '40px',
                overflow: 'hidden'
              },
              dom: `<a href="https://visactor.com/vchart/demo/line-chart/dash-line">${label}</a>`
            }
          };
        }
      }
    }
  ],
  line: {
    style: {
      lineDash: data => {
        if (data.latest) {
          return [5, 5];
        }
        return [0];
      }
    }
  }
};

const vchart = new VChart(spec, { dom: CONTAINER_ID, enableHtmlAttribute: true });
vchart.renderSync();

// Just for the convenience of console debugging, DO NOT COPY!
window['vchart'] = vchart;

相关文档