在vue组件里面如何用canvas实现圆形倒计时效果?

在vue组件里面如何用canvas实现圆形倒计时效果?就是这样的:图片描述

阅读 9.8k
5 个回答

还是svg的效果最好,过渡平滑,而且运动曲线和动画时长均可在CSS中自定义

canvas和css虽然也可以实现,但都很难做到过渡平滑,曲线平滑和自定义运动曲线。

示例如下:

https://codepen.io/zmayor/pen...

圆环用svg更简洁,效果好,参考张鑫旭的文章。
然后,实现倒计时,也就是圆环弧度的动态变化,理清思路就行了,
然而这些跟vue都没有任何关系,
如果要封装成vue组件,按照vue组件规范就行了(模版,样式,逻辑)。
最后,贴一个之前写的圆环的vue组件,仅作参考:

<template>
  <svg class="ring-container" :style="`width: ${size}; height: ${size}`">
    <circle :cx="cx" :cy="cx" :r="r"
            :stroke="backgroundColor"
            :stroke-width="width"
            stroke-linecap="round"
            fill="transparent"></circle>
    <circle :cx="cx" :cy="cx" :r="r"
            class="ring"
            :stroke-width="width"
            :stroke="rate === 0 ? 'transparent': color"
            :style="`stroke-dasharray: ${arc} ${per}`"
            stroke-linecap="round"
            fill="transparent"></circle>
  </svg>
</template>

<script type="text/ecmascript-6">
  import styleConfig from 'config/style'

  export default {
    computed: {
      cx() { // 中心点位置
        return this.size / 2
      },
      r() { // 半径
        return this.size / 2 - this.width
      },
      per() { // 周长
        return parseInt(this.r * Math.PI * 2)
      },
      arc() { // 弧长
        return parseInt(this.per * (this.rate === 0 ? 0 : this.rate / 100))
      }
    },
    props: {
      size: {
        type: Number,
        default: 100
      },
      width: {
        type: Number,
        default: 5
      },
      rate: {
        type: Number,
        default: 0
      },
      color: {
        type: String,
        default: styleConfig.primaryColor
      },
      backgroundColor: {
        type: String,
        default: styleConfig.borderColor
      }
    }
  }
</script>

<style lang="less" rel="stylesheet/less">
  @import "../../less/config";

  .ring-container {
    .ring {
      transform: rotate(-89deg);
      transform-origin: 50% 50%;
      transition: all 1s;
    }
  }
</style>
新手上路,请多包涵
新手上路,请多包涵

canvas+vue组建生成的倒计时,时间和实际时间相比偏快,比如说倒计时60s会比实际时间快上1s,这是怎么回事

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题