在Vue中使用Canvas绘制环形图

本文介绍如何在Vue项目中使用Canvas绘制环形图,包括模板、脚本和CSS部分的实现,详细讲解了创建带有渐变、内阴影、数据填充及中间挖空效果的环形图,并阐述了添加延长线和文字的方法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

环形图组件

1、template 部分

<div class="pie-contain" :style="containSty">
      <canvas
        :id="canvasId"
        :width="width"
        :height="height"
      ></canvas>
      <!-- 中间文字显示 -->
      <div class="pie-text">
        <div class="pie-text-num">{
  { totalValue }}</div>
        <div
          class="pie-text-word"
          v-html="centerT"
        ></div>
      </div>
    </div>

2、script 部分

  • 绘制带有渐变、内阴影的圆
  • 绘制带有数据的圆,填充颜色透明
  • 中间圆挖空,为环形图
  • 再画延长线、文字等
export default {
   
  props: {
   
    canvasId: {
   
      type: String,
      default: "",
    },
    width: {
   
      type: [String, Number],
      default: "",
    },
    height: {
   
      type: [String, Number],
      default: "",
    },
    type: {
   
      type: String,
      default: "ring", // 圆环ring
    },
    data: {
   
      // 存放图表数据
      type: Array,
      default () {
   
        return [];
      },
    },
    options: {
   
      type: Object,
      required: false,
    },
    centerText: {
   
      type: String,
      default: "",
    },
  },
  data () {
   
    return {
   
      canvas: "",
      ctx: "",
      centerT: "",
      colors: [
        {
   
          star: "rgb(82, 241, 243)",
          center: "rgb(43, 139, 148)",
          end: "rgb(7, 54, 59)",
          rect: "rgb(80, 252, 254)",
        },
        {
   
          star: "rgb(8, 53, 59)",
          center: "rgb(9, 60, 66)",
          end: "rgb(9, 58, 63)",
          rect: "rgb(48, 146, 155)",
        },
      ], // 环形图颜色列表
    };
  },
  mounted () {
   
    this.sChart(this.canvasId, this.type, this.data, this.options);
  },
  computed: {
   
    /**
     * 获取饼状或环形图的数据总和
     * @return {Number} total
     */
    totalValue () {
   
      let total = 0;
      for (let i = 0; i < this.data.length; i++) {
   
        total += this.data[i].value;
      }
      return total;
    },
    // 容器宽高
    containSty () {
   
      const style = {
   };
      style.width = this.width + "px";
      style.height = this.height + "px";
      return style;
    },
  },
  methods: {
   
    sChart (canvas, type, data, options) {
   
      this.canvas = document.getElementById(canvas);
      this.ctx = this.canvas.getContext("2d");
      
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值