uni-app 虚线圆环进度条插件需求

发布于 1周前 作者 caililin 来自 Uni-App

uni-app 虚线圆环进度条插件需求

虚线圆环进度条

1 回复

针对您提出的uni-app虚线圆环进度条插件需求,以下是一个基于Canvas和JavaScript实现的代码案例。该代码将展示如何在uni-app中创建一个自定义组件,用于渲染虚线圆环进度条。

首先,创建一个名为DottedCircleProgress.vue的自定义组件:

<template>
  <view class="container">
    <canvas canvas-id="dottedCircleCanvas" style="width: 100%; height: 100%;"></canvas>
  </view>
</template>

<script>
export default {
  props: {
    progress: {
      type: Number,
      default: 0
    },
    strokeWidth: {
      type: Number,
      default: 5
    },
    radius: {
      type: Number,
      default: 50
    },
    lineLength: {
      type: Number,
      default: 10
    },
    lineSpacing: {
      type: Number,
      default: 5
    }
  },
  mounted() {
    this.drawDottedCircleProgress();
  },
  watch: {
    progress() {
      this.drawDottedCircleProgress();
    }
  },
  methods: {
    drawDottedCircleProgress() {
      const ctx = uni.createCanvasContext('dottedCircleCanvas');
      const { progress, strokeWidth, radius, lineLength, lineSpacing } = this;
      const totalLength = 2 * Math.PI * radius;
      const drawnLength = totalLength * (progress / 100);
      const dashArray = [];
      let dashOffset = 0;

      for (let i = 0; i < drawnLength / (lineLength + lineSpacing); i++) {
        dashArray.push(lineLength, lineSpacing);
      }
      if (drawnLength % (lineLength + lineSpacing) > lineLength / 2) {
        dashArray.push(drawnLength % (lineLength + lineSpacing) - lineSpacing);
      } else {
        dashOffset = lineLength / 2 - (drawnLength % (lineLength + lineSpacing));
      }

      ctx.setStrokeStyle('#3498db');
      ctx.setLineWidth(strokeWidth);
      ctx.setLineCap('round');
      ctx.setLineDash(dashArray);
      ctx.setLineDashOffset(dashOffset);
      ctx.beginPath();
      ctx.arc(radius, radius, radius, 0, 2 * Math.PI);
      ctx.stroke();
      ctx.draw();
    }
  }
};
</script>

<style>
.container {
  display: flex;
  justify-content: center;
  align-items: center;
  width: 100%;
  height: 100%;
}
</style>

在上述代码中,我们定义了一个DottedCircleProgress组件,它接收progressstrokeWidthradiuslineLengthlineSpacing作为属性。组件在挂载时以及progress属性变化时会调用drawDottedCircleProgress方法来绘制虚线圆环进度条。

使用Canvas的setLineDashsetLineDashOffset方法来实现虚线效果,并根据进度计算虚线的长度和偏移量。

您可以在uni-app的页面或其他组件中引入并使用这个自定义组件,通过绑定progress属性来控制进度条的显示。例如:

<template>
  <view>
    <DottedCircleProgress :progress="50" />
  </view>
</template>

<script>
import DottedCircleProgress from '@/components/DottedCircleProgress.vue';

export default {
  components: {
    DottedCircleProgress
  }
};
</script>

这样,您就可以在uni-app项目中轻松实现虚线圆环进度条功能。

回到顶部