小程序 mpvue 使用canvas绘制环形图表

本来想用css3来实现,发现轮廓边上残影严重,所以直接用小程序的canvas使用来。
最终效果如下:
在这里插入图片描述
我的整页代码如下,里面已经写出备注来。

<template>
  <div class="statistic">
    <canvas canvas-id="runCanvas" id="runCanvas" class='canvas'>
    </canvas>
  </div>
</template>
<script>

export default {
  data() {
    return {

    }
  },
  methods: {
    run(x0, y0, nowPercent) {
      // 1° 设置配置参数
      // 环形的线宽度
      const lineWidth = 16;
      // 半径
      const radius = x0 - lineWidth;
      // 起始弧
      const sAngle = -0.5 * Math.PI;
      // 终止弧
      let eAngle = (2 * Math.PI / 100 * nowPercent) - 0.5 * Math.PI;

      // 2° 画圆环阴影
      this.ctx2.setLineWidth(16);
      this.ctx2.setStrokeStyle('#d2d2d2');
      this.ctx2.setLineCap('round')
      this.ctx2.arc(x0, y0, radius, 0, 2 * Math.PI, false);
      //对当前路径进行描
      this.ctx2.stroke();

      // 3° 画圆环激活高亮部分
      this.ctx2.beginPath();//开始一个新的路径
      this.ctx2.setLineWidth(16);
      this.ctx2.setStrokeStyle('#00D49F');
      this.ctx2.setLineCap('round')
      this.ctx2.arc(x0, y0, radius, sAngle, eAngle, false);
      this.ctx2.stroke();

      // 4° 设置环心字体
      this.ctx2.beginPath();
      // 字体大小 注意不要加引号
      this.ctx2.font = 'normal bold 40px sans-serif';
      // 字体颜色
      this.ctx2.setFillStyle("#00D49F");
      // 字体位置
      this.ctx2.setTextAlign("center");
      // 字体对齐方式
      this.ctx2.setTextBaseline("middle");
      // 文字内容和文字坐标
      this.ctx2.fillText(nowPercent + "%", x0, y0);

      // 5°最后通过draw把上面的描述绘制出来
      this.ctx2.draw();
    },

    draw(id, percent) {
      this.ctx2 = wx.createCanvasContext(id);
      const that = this;
      wx.createSelectorQuery().select('#' + id).boundingClientRect(function (rect) { //监听canvas的宽高
        // 获取圆心坐标
        var x0 = parseInt(rect.width / 2); //获取canvas宽的的一半
        var y0 = parseInt(rect.height / 2); //获取canvas高的一半,
        // 开始画画
        that.run(x0, y0, percent);
      }).exec();
    },

  },
  mounted() {
    this.draw('runCanvas', 50);
  }
}
</script>

<style lang="less" scoped>
  .canvas {
    width: 150px;
    height: 150px;
    position: absolute;
    left: 0;
    top: 0;
    bottom: 0;
    right: 0;
    margin: auto auto;
    z-index: 99;
  }
</style>
<style lang="less">
  page {
    background: white;
  }
</style>




  • 4
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值