如何用 Vue.js 将后端 JSON 实时绑定到 SVG 饼图,并添加过渡动画?

解读

国内一线公司面试时,这道题考察的不仅是“把数据画成图”,而是“把数据、视图、动画、性能、工程化”五个维度一次性串起来。

  1. 实时:WebSocket 或 SSE 推送,不能轮询。
  2. JSON:字段必须可扩展(名称、值、色值、标签),不能写死。
  3. SVG:必须用原生 <path> 画扇形,不能用第三方图表库;Inkscape 生态里随时要导出纯 SVG 给激光切割,路径必须干净、无冗余变换。
  4. Vue:响应式驱动,禁止直接操作 DOM,动画用 <transition> + CSS 或 GSAP,但要保留 Vue 的数据追踪。
  5. 过渡动画:扇形从 0° 展开到目标角度,同时颜色淡入,时长 600 ms,需兼容 60 fps 低端国产机。

知识点

  • Vue3 组合式 API:reactive、watch、nextTick、onMounted、onBeforeUnmount
  • 实时通道:WebSocket 浏览器兼容、心跳重连、二进制掩码处理
  • SVG 路径命令:M L A Z 的极坐标与直角坐标互算,大弧标志、角度转弧度
  • 动画策略:CSS stroke-dasharray 遮罩方案、Vue <transition> 的 enter-active-class、GSAP 3 drawSVG 插件
  • 性能:路径缓存、防抖、RAF 批量写入、will-change 提示合成层
  • 工程化:Vite 代理 WebSocket、TypeScript 类型声明、ESLint 规则 @typescript-eslint/no-non-null-assertion
  • 可访问性:<title> 标签、aria-label、键盘焦点高亮
  • 国产化:鸿蒙 2 内置浏览器不支持 OffscreenCanvas,必须降级 SVG 动画

答案

  1. 协议与类型
// src/types/pie.ts
export interface PieSector {
  name: string
  value: number
  color: string
}
export interface PieFrame {
  timestamp: number
  data: PieSector[]
}
  1. WebSocket 封装
// src/composables/usePieSocket.ts
import { reactive, onMounted, onBeforeUnmount } from 'vue'

export default function usePieSocket(url: string) {
  const state = reactive<{ frame: PieFrame | null }>({ frame: null })
  let ws: WebSocket | null = null
  let heart: number

  const connect = () => {
    ws = new WebSocket(url)
    ws.binaryType = 'arraybuffer'
    ws.onmessage = (e) => {
      const txt = new TextDecoder().decode(e.data)
      state.frame = JSON.parse(txt) as PieFrame
    }
    ws.onclose = () => clearInterval(heart)
    ws.onopen = () => heart = window.setInterval(() => ws!.send('ping'), 30000)
  }
  onMounted(connect)
  onBeforeUnmount(() => ws?.close())
  return state
}
  1. 扇形路径计算
// src/utils/svgPie.ts
export function polarToCartesian(cx: number, cy: number, r: number, angleDeg: number) {
  const a = (angleDeg - 90) * Math.PI / 180
  return { x: cx + r * Math.cos(a), y: cy + r * Math.sin(a) }
}

export function describeArc(cx: number, cy: number, r: number, start: number, end: number) {
  const s = polarToCartesian(cx, cy, r, end)
  const e = polarToCartesian(cx, cy, r, start)
  const large = end - start > 180 ? 1 : 0
  return `M ${cx} ${cy} L ${s.x} ${s.y} A ${r} ${r} 0 ${large} 0 ${e.x} ${e.y} Z`
}
  1. Vue 组件
<!-- src/components/LivePie.vue -->
<template>
  <svg viewBox="0 0 400 400" width="100%" height="100%">
    <g v-for="(s,i) in sectors" :key="s.name">
      <transition appear @enter="enter" :css="false">
        <path :d="s.d" :fill="s.color" opacity="0" :ref="setPathRef" />
      </transition>
      <title>{{ s.name }} {{ s.value }}</title>
    </g>
  </svg>
</template>

<script setup lang="ts">
import { computed, nextTick } from 'vue'
import gsap from 'gsap'
import usePieSocket from '@/composables/usePieSocket'
import { describeArc } from '@/utils/svgPie'

const { frame } = usePieSocket('wss://api.xxx.com/live-pie')

const sectors = computed(() => {
  if (!frame.value) return []
  const total = frame.value.data.reduce((a, b) => a + b.value, 0)
  let acc = 0
  return frame.value.data.map(d => {
    const start = acc
    const end = acc + d.value / total * 360
    acc = end
    return { ...d, d: describeArc(200, 200, 150, start, end) }
  })
})

let pathList: SVGPathElement[] = []
const setPathRef = (el: any) => el && pathList.push(el)

function enter(el: SVGPathElement, done: () => void) {
  const l = el.getTotalLength()
  gsap.set(el, { strokeDasharray: l, strokeDashoffset: l, opacity: 1 })
  gsap.to(el, {
    strokeDashoffset: 0,
    duration: 0.6,
    ease: 'power2.out',
    onComplete: done
  })
}

nextTick(() => pathList = [])
</script>
  1. 性能与降级
  • 扇形数量 > 50 时改用 requestAnimationFrame 批量绘制,避免 Vue 的 50 次 reactive 触发。
  • 低端机不支持 GSAP,则回退 CSS @keyframes 并关闭 stroke-dasharray,改用 transform: scale 从 0 到 1。

拓展思考

  1. 如果后端推送频率 30 fps,前端如何降采样到 5 fps 而不丢关键帧?
    答:在 usePieSocket 内做时间窗口滑动,保留最新完整帧,用 requestAnimationFrame 按屏幕刷新率采样。

  2. 激光切割要求路径闭合且不能自交,如何验证?
    答:用 opentype.js 的 Path 类计算面积符号,若扇形面积为负则反向,保证逆时针;再用 Shoelace 算法检测自交。

  3. 需要导出为 Inkscape 可编辑的 SVG,如何保留图层名?
    答:把扇形包在 <g id="layer{{index}}" inkscape:label="sector{{name}}"> 中,并在 <style> 里写 inkscape:label 作为元数据,Vue 渲染时动态注入。

  4. 面试追问:若产品要求 3D 饼图?
    答:仍用 SVG 的 transform3d 伪 3D,或输出路径给 Blender 的 Inkscape 插件,前端只负责实时更新角度参数,不直接渲染 WebGL,保持与激光切割同源数据。