事先说明,antv f2 虽然专为移动端设计,但当前文档还是个草稿,只看文档可能各种报错。而且据我使用,有些功能是缺失的,比如文档中写的事件支持,我是没能成功触发。所以 antv f2 对于只显示数据、只使用基本交互,不需要添加自定义事件的业务很适用,否则换 echarts 吧。

效果图如下(上传的 apng 被思否压缩破坏了动态性,可点击链接直接打开动态图):

查看图片

output

1 安装依赖

pnpm i @antv/f2 taro-f2-react

2 编写代码

通过setTimeout模拟数据更新。

import React, { useEffect, useState } from 'react'
import { View } from '@tarojs/components'
import { getCurrentPages } from '@tarojs/taro'
import {
  Chart, Axis, Area, Point, Line,
} from '@antv/f2'
import F2Canvas from 'taro-f2-react'
import { max as getMax } from '@/utils'
import { generateColors } from '@/utils/color'
import { randomInt } from '@/utils/random'

interface RadarChartProps {
  max: number
  data: { item: string, score: number }[]
}

const colors = generateColors(9)

const initProps = {"max":9,"data":[{"item":"和平型","score":4},{"item":"完美主义者","score":8},{"item":"智慧型","score":5},{"item":"活跃型","score":6},{"item":"领袖型","score":9},{"item":"全爱自助型","score":5},{"item":"自我型","score":8},{"item":"忠诚型","score":7},{"item":"成就型","score":8}]}

const RadarChart = ({ max, data }: RadarChartProps) => {
  const sorted = data.sort((a, b) => b.score - a.score)

  return (
    <Chart
      data={data}
      coord='polar'
      scale={{
        score: {
          min: 0,
          max: max,
          nice: true,
          tickCount: Math.ceil(max / 3),
        },
      }}
    >
      <Axis field='item' />

      <Axis field='score' />

      <Line x='item' y='score' />

      <Area x='item' y='score' />

      <Point
        x='item'
        y='score'
        color={{
          field: 'item',
          callback: (v: string) => {
            const color = colors[sorted.findIndex(i => i.item === v)]

            return color
          },
        }}
      />
    </Chart>
  )
}

const Result = () => {
  const [chartProps, setChartProps] = useState<RadarChartProps>(initProps)

  useEffect(() => {
    const timer = setTimeout(() => {
      setChartProps(pre => {
        const data = pre!.data.map(v => ({ ...v, score: randomInt(0, 13) }))
        const max = getMax(data, 'score')!.score

        return { max, data }
      })
    }, 2000)

    return () => clearTimeout(timer)
  }, [])

  return (
    <View>
          <View style={{ width: '100%', height: '500rpx' }}>
            <F2Canvas>
              <RadarChart
                {...chartProps}
              />
            </F2Canvas>
          </View>
    </View>
  )
}

export default Result

thepoy
156 声望33 粉丝