以下是Vue.js中使用canvas绘制倒计时30秒的示例代码:

<template>
  <div>
    <canvas ref="canvas" width="200" height="200"></canvas>
    <div>{{ remainingTime }}</div>
  </div>
</template>

<script>
export default {
  data() {
    return {
      remainingTime: 30,
      timer: null,
    };
  },
  mounted() {
    this.drawTimer();
    this.startTimer();
  },
  methods: {
    drawTimer() {
      const canvas = this.$refs.canvas;
      const context = canvas.getContext('2d');
      const centerX = canvas.width / 2;
      const centerY = canvas.height / 2;
      const radius = 80;

      context.beginPath();
      context.arc(centerX, centerY, radius, 0, 2 * Math.PI);
      context.fillStyle = '#ccc';
      context.fill();

      context.beginPath();
      context.moveTo(centerX, centerY);
      const endAngle = -((2 * Math.PI) / 30) * (30 - this.remainingTime) - Math.PI / 2;
      context.arc(centerX, centerY, radius, -Math.PI / 2, endAngle);
      context.fillStyle = '#ff0000';
      context.fill();
    },
    startTimer() {
      this.timer = setInterval(() => {
        this.remainingTime--;
        this.drawTimer();
        if (this.remainingTime <= 0) {
          clearInterval(this.timer);
        }
      }, 1000);
    },
  },
};
</script>

<style scoped>
canvas {
  border: 1px solid #ccc;
}
</style>

在上面的示例中,首先定义了一个canvas元素和一个显示剩余时间的div元素。然后在mounted钩子函数中调用了drawTimer方法绘制倒计时的圆圈。drawTimer方法使用canvas的getContext方法获取绘图上下文,然后使用arc方法绘制圆圈,并根据剩余时间计算出需要绘制的圆弧的结束角度,填充颜色为红色。

接着在startTimer方法中使用setInterval方法每秒减少剩余时间并重新绘制倒计时的圆弧,直到剩余时间为0时清除计时器。

最后,在样式中设置canvas的边框样式

vue canvas 绘制倒计时30s

原文地址: https://www.cveoy.top/t/topic/izNN 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录