ant design charts部分自定义样式

5,484 阅读4分钟

在上一篇文章中,我们介绍了ant design charts的安装及基本用法。本次将结合示例介绍一些常用图表组件的自定义样式使用。

ant design charts图表示例

1.ant design charts自定义tooltips样式

tooltips是ant design charts的基础图表组件,我们在大多数图表中都能见到它的身影。其作用是鼠标移入图表相应区域时显示数据详情。在config中如果不配置,将显示默认样式。

image.png

image.png

如果我们不想使用tooltips的默认样式,我们需要通过tooltips中的customContent方法来进行自定义样式。

此段代码直接放入config中即可

    tooltip: {
      //customContent方法有两个参数,从中我们可以取到当前选中的行列所对应的值,及对应的色块颜色
      customContent: (title, items) => { 
        return (
          <>
          <div style={  //此处配置弹窗的基本样式,如宽高,背景及文字颜色等
            {
              width: 106,
              // height: 132,
              padding: 10,
              backgroundColor: 'rgba(0, 0, 0, 0.75)',
              color: 'white',
              fontSize: 12,
              margin: '0 -12px 0 -12px',
              borderRadius: 2,
              }}>
            <h5 style={{ marginTop: 0, color: 'white'}}>{title}</h5>
            <ul style={{ paddingLeft: 0 }}>
              {items?.map((item, index) => {
                const { name, value, color } = item; //我们可以从name, value, color取到想要的值
                return (
                  <li
                    key={item.year}
                    className="g2-tooltip-list-item"
                    data-index={index}
                    style={{ marginBottom: 4, display: 'flex', alignItems: 'center' }}
                  >
                    <span className="g2-tooltip-marker" style={{ backgroundColor: color }}></span>
                    <span
                      style={{ display: 'inline-flex', flex: 1, justifyContent: 'space-between' }}
                    >
                      <span style={{ margiRight: 16 }}>{name}:</span>
                      <span className="g2-tooltip-list-item-value">{value}</span>
                    </span>
                  </li>
                );
              })}
            </ul>
            </div>
          </>
        );
      },
    },

自定义样式如下:

image.png 从代码中我们可以看到,实际项目中,我们可以根据需求通过customContent对tooltips样式进行自定义。由于tooltips是ant design charts的基础图表组件,因此只要支持tooltips的图表,均可使用此种方法自定义样式。

2.对元素添加点击事件

ant design charts中几乎所有实例都可通过onReady获取

  ```
const clickTag = (evt) => {
 console.log(evt);
};

return (
    <Column
      {...config}
      onReady={(plot) => {
        plot.on('plot:click', (evt) => {
          const { x, y } = evt;
          const { xField } = plot.options;
          const tooltipData = plot.chart.getTooltipItems({ x, y });
          console.log(tooltipData);
              clickTag(evt); //点击方法
        });
      }}
    />
  );
```

3.混合图表

混合图表的使用与普通图表类似,区别仅在于混合图表需传入两组数据来实现。 如果你既想看到多种数据的对比,又想看到总量的变化趋势,这时就可使用这种堆叠柱线混合图表:

image.png

import React, { useState, useEffect } from 'react';
import ReactDOM from 'react-dom';
import { DualAxes } from '@ant-design/charts';

const DemoDualAxes = () => {
  const uvBillData = [
    {
      time: '2019-03',
      value: 350,
      type: 'uv',
    },
    {
      time: '2019-04',
      value: 900,
      type: 'uv',
    },
    {
      time: '2019-05',
      value: 300,
      type: 'uv',
    },
    {
      time: '2019-06',
      value: 450,
      type: 'uv',
    },
    {
      time: '2019-07',
      value: 470,
      type: 'uv',
    },
    {
      time: '2019-03',
      value: 220,
      type: 'bill',
    },
    {
      time: '2019-04',
      value: 300,
      type: 'bill',
    },
    {
      time: '2019-05',
      value: 250,
      type: 'bill',
    },
    {
      time: '2019-06',
      value: 220,
      type: 'bill',
    },
    {
      time: '2019-07',
      value: 362,
      type: 'bill',
    },
  ];
  const transformData = [
    {
      time: '2019-03',
      count: 550,
    },
    {
      time: '2019-04',
      count: 1200,
    },
    {
      time: '2019-05',
      count: 550,
    },
    {
      time: '2019-06',
      count: 670,
    },
    {
      time: '2019-07',
      count: 832,
    },
  ];
  const config = {
    data: [uvBillData, transformData], //分别对应柱状图和折线图的数据
    xField: 'time',
    yField: ['value', 'count'],
    yAxis: { // 混合图表实际上不是共用一个面板,柱状图数值默认从0开始,而折线图从最小值开始
     count: { // 若想两侧数据对齐,需设置折线图数据最小值从0开始
      min: 0, 
     },
    },
    geometryOptions: [
      { //柱状图配置
        geometry: 'column',
        isStack: true,
        seriesField: 'type',
      },
      { //折线图配置
        geometry: 'line',
      },
    ],
  };
  return <DualAxes {...config} />;
};

ReactDOM.render(<DemoDualAxes />, document.getElementById('container'));

4.水波图自定义样式

水波图通常用于展示系统容量,下面将展示如何对水波图的标题,内容,形状以及颜色进行自定义样式,大家可结合注释调整样式:

import React, { useState, useEffect } from 'react';
import ReactDOM from 'react-dom';
import { Liquid, measureTextWidth } from '@ant-design/charts';

const DemoLiquid = () => {
  const config = {
    percent: 0.25,                          //百分比显示数据
    shape: function (x, y, width, height) { //用于改变水波图默认形状,不设置默认为圆形
      const r = width / 4;
      const dx = x - width / 2;
      const dy = y - height / 2;
      return [
        ['M', dx, dy + r * 2],
        ['A', r, r, 0, 0, 1, x, dy + r],
        ['A', r, r, 0, 0, 1, dx + width, dy + r * 2],
        ['L', x, dy + height],
        ['L', dx, dy + r * 2],
        ['Z'],
      ];
    },
    statistic: {                   //中心文本组件,包含标题和内容
      title: {                     //自定义标题
        formatter: function formatter () {
          return '系统剩余空间';
        },
        style: function style () { //自定义标题样式
          return {
            fontSize: 12,
            fill: '#999999',
            textShadow: 'none',
          };
        },
      },
      content: { //自定义内容
        style: function style () { //自定义内容样式
          return {
            fontSize: 24,
            lineHeight: 1, 
            fill: 'color: rgba(0, 0, 0, 0.85);',
          };
        },
        //自定义主体文本的 html,优先级高于 formatter
        customHtml: function customHtml (container, view, _ref3) {  
          var percent = _ref3.percent;
          var _container$getBoundin = container.getBoundingClientRect();
          var width = _container$getBoundin.width;
          var height = _container$getBoundin.height;
          var d = Math.sqrt(Math.pow(width / 2, 2) + Math.pow(height / 2, 2));
          var text = ''.concat(((1 - percent) * 100).toFixed(2));
          var textWidth = (0, measureTextWidth)(text, { fontSize: 40 });
          var scale = Math.min(d / textWidth, 1);

          // 自定义内容详情
          return '<div style="width:'
            .concat(d, 'px;display:flex;align-items:center;justify-content:center;font-size:')
            .concat(scale, 'em;line-height:')
            .concat(scale <= 1 ? 1 : 'inherit', '">')
            .concat(text, '<span style="font-size:10px;margin-top:5px">%</span></div>');
        },
      },
    },
    outline: {     //外边框样式
      border: 4,   //外边框宽度
      distance: 8, //边框内边距
    },
    wave: { //动态水波的波长
      length: 128,
    },
    liquidStyle: function liquidStyle (_ref4) {   //水波图的配色样式
    var percent = _ref4.percent;

    return {
      fill: percent > 0.45 ? '#3964C5' : '#3964C5',    //填充色,可根据当前百分比改变颜色
      stroke: percent > 0.45 ? '#3964C5' : '#3964C5',  //图形的描边颜色,可根据当前百分比改变颜色
      shadowColor: 'rgba(57, 100, 197, 0.6)',
      shadowBlur: 10,
      shadowOffsetX: 0,
      shadowOffsetY: 0,
    };
    },
  };
  return <Liquid {...config} />;
};

ReactDOM.render(<DemoLiquid />, document.getElementById('container'));

效果图:

image.png

结尾

更多详情请参考:ant design charts图表示例