canvas绘制进度条(wepy)

<template>
  <canvas canvas-id="canvas" style="width:{{width+10}}px;height:{{width+10}}px;"></canvas>
</template>

<script>
import wepy from 'wepy'

export default class CircleProgress extends wepy.component {
  props = {
    progressData: {
      type: Object,
      default: {
        page: 'index',  //  首页 index 复习页 review
        deg: 0 //  进度 0 - 1
      }
    }
  }
  data = {
    ctx: null
  }
  watch = {
    progressData(newValue) {
      this.methods.drawCanvas(newValue, this)
    }
  }
  computed = {
    width() {
      return this.progressData.page === 'index' ? 196 : 120
    }
  }
  methods = {
    drawCanvas(data, This) {
      let { page, deg } = data
      if (!deg) deg = 0
      const r = page === 'index' ? 98 : 60  //  半径
      const pw = page === 'index' ? 6 : 5  //  进度条宽度
      const bgc = page === 'index' ? '#FFE14F' : deg === 0 ? '#3EDA69' : '#F8F8F8'  //  进度条背景颜色
      const pc = page === 'index' ? '#fff' : '#FF6036'  //  进度颜色
      let ctx
      if (This.ctx) {
        ctx = This.ctx
      } else {
        ctx = wepy.createCanvasContext('canvas', This)
      }
      ctx.strokeStyle = bgc
      ctx.setLineCap('round')
      ctx.setLineWidth(pw)
      //  半径需要减去二分之一的进度条宽度
      ctx.arc(r + 5, r + 5, page === 'index' ? r - 3 : r - 2.5, 0, Math.PI * 2)
      ctx.stroke()
      if (deg !== 0) {
        ctx.beginPath()
        ctx.strokeStyle = pc
        ctx.arc(r + 5, r + 5, page === 'index' ? r - 3 : r - 2.5, Math.PI / 2, Math.PI / 2 + Math.PI * 2 * deg)
        ctx.stroke()
      }
      if (page === 'index') {
        ctx.strokeStyle = '#fff'
        ctx.beginPath()
        ctx.setLineWidth(1)
        ctx.arc(r + 5, r + 5, r, 0, Math.PI * 2)
        ctx.stroke()
        ctx.beginPath()
        ctx.arc(r + 5, r + 5, r - pw, 0, Math.PI * 2)
        ctx.stroke()
        ctx.beginPath()
        const x = r + 5 + (r - 3) * Math.cos(Math.PI / 2 + Math.PI * 2 * deg)
        const y = r + 5 + (r - 3) * Math.sin(Math.PI / 2 + Math.PI * 2 * deg)
        ctx.arc(x, y, 6, 0, Math.PI * 2)
        ctx.setFillStyle('#fff')
        ctx.fill()
      }
      ctx.draw()
    }
  }
}
</script>

<style lang="less">
  canvas {
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%,-50%);
  }
</style>

 

posted @ 2018-08-23 16:10  花开半夏shen  阅读(448)  评论(0编辑  收藏  举报