博客 / 詳情

返回

微信小程序 taro + react + antv-f2 繪製圖表

事先説明,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
user avatar
0 位用戶收藏了這個故事!

發佈 評論

Some HTML is okay.