当前位置:首页 > VUE

vue 实现扇形图表

2026-01-18 08:57:36VUE

使用 SVG 和 Vue 实现扇形图表

在 Vue 中实现扇形图表可以通过 SVG 的 <path> 元素结合计算属性动态生成扇形路径。以下是一个完整的实现示例:

<template>
  <div class="pie-chart">
    <svg width="400" height="400" viewBox="0 0 400 400">
      <path
        v-for="(item, index) in sectors"
        :key="index"
        :d="item.path"
        :fill="item.color"
        @mouseover="handleHover(index)"
      />
    </svg>
    <div class="legend">
      <div v-for="(item, index) in data" :key="index" class="legend-item">
        <span :style="{ backgroundColor: colors[index] }"></span>
        {{ item.label }}: {{ item.value }}
      </div>
    </div>
  </div>
</template>

<script>
export default {
  props: {
    data: {
      type: Array,
      required: true
    },
    colors: {
      type: Array,
      default: () => ['#FF6384', '#36A2EB', '#FFCE56', '#4BC0C0', '#9966FF']
    }
  },
  computed: {
    sectors() {
      const total = this.data.reduce((sum, item) => sum + item.value, 0);
      let cumulativeAngle = 0;

      return this.data.map((item, index) => {
        const angle = (item.value / total) * 360;
        const path = this.describeArc(200, 200, 150, cumulativeAngle, cumulativeAngle + angle);
        cumulativeAngle += angle;

        return {
          path,
          color: this.colors[index % this.colors.length]
        };
      });
    }
  },
  methods: {
    polarToCartesian(centerX, centerY, radius, angleInDegrees) {
      const angleInRadians = (angleInDegrees - 90) * Math.PI / 180;
      return {
        x: centerX + (radius * Math.cos(angleInRadians)),
        y: centerY + (radius * Math.sin(angleInRadians))
      };
    },

    describeArc(x, y, radius, startAngle, endAngle) {
      const start = this.polarToCartesian(x, y, radius, endAngle);
      const end = this.polarToCartesian(x, y, radius, startAngle);
      const largeArcFlag = endAngle - startAngle <= 180 ? '0' : '1';

      return [
        'M', x, y,
        'L', end.x, end.y,
        'A', radius, radius, 0, largeArcFlag, 0, start.x, start.y,
        'Z'
      ].join(' ');
    },

    handleHover(index) {
      this.$emit('sector-hover', this.data[index]);
    }
  }
};
</script>

<style>
.pie-chart {
  display: flex;
  align-items: center;
  justify-content: center;
  flex-direction: column;
}

.legend {
  margin-top: 20px;
  display: flex;
  flex-wrap: wrap;
  justify-content: center;
}

.legend-item {
  display: flex;
  align-items: center;
  margin: 0 10px;
}

.legend-item span {
  display: inline-block;
  width: 12px;
  height: 12px;
  margin-right: 5px;
  border-radius: 2px;
}
</style>

使用第三方库(如 ECharts)实现

对于更复杂的扇形图表需求,可以使用 ECharts 这样的专业图表库:

<template>
  <div ref="chart" style="width: 600px; height: 400px;"></div>
</template>

<script>
import * as echarts from 'echarts';

export default {
  props: {
    data: {
      type: Array,
      required: true
    }
  },
  mounted() {
    this.initChart();
  },
  methods: {
    initChart() {
      const chart = echarts.init(this.$refs.chart);
      const option = {
        tooltip: {
          trigger: 'item',
          formatter: '{a} <br/>{b}: {c} ({d}%)'
        },
        legend: {
          orient: 'vertical',
          left: 10,
          data: this.data.map(item => item.label)
        },
        series: [
          {
            name: '数据',
            type: 'pie',
            radius: ['50%', '70%'],
            avoidLabelOverlap: false,
            label: {
              show: false,
              position: 'center'
            },
            emphasis: {
              label: {
                show: true,
                fontSize: '18',
                fontWeight: 'bold'
              }
            },
            labelLine: {
              show: false
            },
            data: this.data.map(item => ({
              value: item.value,
              name: item.label
            }))
          }
        ]
      };
      chart.setOption(option);
    }
  },
  watch: {
    data: {
      handler() {
        this.initChart();
      },
      deep: true
    }
  }
};
</script>

实现动画效果

为扇形图表添加动画效果可以增强用户体验:

<script>
// 在SVG实现的组件中添加动画方法
methods: {
  animateChart() {
    this.animationProgress = 0;
    const duration = 1000; // 动画持续时间(ms)
    const steps = 60; // 动画帧数
    const stepSize = 1 / steps;

    const animate = () => {
      this.animationProgress += stepSize;
      if (this.animationProgress < 1) {
        requestAnimationFrame(animate);
      }
    };

    animate();
  }
},
computed: {
  sectors() {
    // 修改计算逻辑以支持动画
    const total = this.data.reduce((sum, item) => sum + item.value, 0);
    let cumulativeAngle = 0;

    return this.data.map((item, index) => {
      const fullAngle = (item.value / total) * 360;
      const currentAngle = fullAngle * this.animationProgress;
      const path = this.describeArc(200, 200, 150, cumulativeAngle, cumulativeAngle + currentAngle);
      cumulativeAngle += fullAngle;

      return {
        path,
        color: this.colors[index % this.colors.length]
      };
    });
  }
},
mounted() {
  this.animateChart();
}
</script>

响应式设计

确保图表在不同屏幕尺寸下正常显示:

<script>
// 在ECharts实现的组件中添加
methods: {
  handleResize() {
    if (this.chart) {
      this.chart.resize();
    }
  }
},
mounted() {
  this.initChart();
  window.addEventListener('resize', this.handleResize);
},
beforeDestroy() {
  window.removeEventListener('resize', this.handleResize);
  if (this.chart) {
    this.chart.dispose();
  }
}
</script>

这些实现方法涵盖了从基础SVG绘制到使用专业库的不同方案,可以根据项目需求选择合适的实现方式。

vue 实现扇形图表

标签: 扇形图表
分享给朋友:

相关文章

js实现图表

js实现图表

在JavaScript中实现图表通常使用流行的图表库,以下是几种常见的方法和工具: 使用Chart.js Chart.js是一个简单灵活的库,适合快速生成响应式图表。安装方式包括CDN引入或npm…

jquery 图表

jquery 图表

jQuery 图表库推荐 jQuery 本身不直接提供图表功能,但可以通过插件或集成其他库实现图表绘制。以下是几种常用的 jQuery 图表解决方案: Chart.js 集成 Chart.js 是…

vue实现扇形进度

vue实现扇形进度

Vue 实现扇形进度条 使用 SVG 绘制扇形 SVG 的 path 元素可以用于绘制扇形。通过计算扇形的路径数据,结合 Vue 的动态数据绑定实现进度变化。 <template>…

vue实现扇形图表

vue实现扇形图表

实现扇形图表的方法 在Vue中实现扇形图表可以通过多种方式完成,常见的方法包括使用第三方图表库或自定义SVG绘制。以下是两种常用的实现方式。 使用ECharts库 ECharts是一个功能强大的图…

css制作扇形

css制作扇形

使用 CSS 制作扇形的方法 通过 CSS 的 border-radius 和 transform 属性可以轻松实现扇形效果。以下是几种常见的实现方式: 方法一:使用 border-radius 和…

css制作扇形图

css制作扇形图

使用CSS制作扇形图 使用CSS的clip-path属性可以轻松创建扇形图。通过定义多边形的顶点坐标,可以裁剪元素为扇形形状。 <div class="pie-chart"></…