<template>
  <div>
    <canvas ref="canvas" width="200" height="200"></canvas>
  </div>
</template>
<script>
export default {
  mounted() {
    this.drawCountdown();
  },
  methods: {
    drawCountdown() {
      const canvas = this.$refs.canvas;
      const ctx = canvas.getContext('2d');
      const radius = canvas.width / 2;

      // 绘制倒计时背景
      ctx.beginPath();
      ctx.arc(radius, radius, radius, 0, 2 * Math.PI);
      ctx.fillStyle = '#f1f1f1';
      ctx.fill();

      // 获取当前时间
      const now = new Date();
      const hours = now.getHours();
      const minutes = now.getMinutes();
      const seconds = now.getSeconds();

      // 绘制时钟
      this.drawClock(ctx, radius);

      // 绘制时针
      this.drawHand(ctx, radius * 0.5, hours * 30 + minutes * 0.5);

      // 绘制分针
      this.drawHand(ctx, radius * 0.7, minutes * 6);

      // 绘制秒针
      this.drawHand(ctx, radius * 0.9, seconds * 6);
    },
    drawClock(ctx, radius) {
      ctx.beginPath();
      ctx.arc(radius, radius, radius * 0.05, 0, 2 * Math.PI);
      ctx.fillStyle = '#333';
      ctx.fill();

      ctx.font = '16px Arial';
      ctx.textAlign = 'center';
      ctx.textBaseline = 'middle';

      for (let i = 1; i <= 12; i++) {
        const angle = i * Math.PI / 6;
        const x = radius + radius * 0.8 * Math.cos(angle);
        const y = radius + radius * 0.8 * Math.sin(angle);
        ctx.fillText(i, x, y);
      }
    },
    drawHand(ctx, length, angle) {
      ctx.beginPath();
      ctx.moveTo(ctx.canvas.width / 2, ctx.canvas.height / 2);
      const x = ctx.canvas.width / 2 + length * Math.cos(angle * Math.PI / 180 - Math.PI / 2);
      const y = ctx.canvas.height / 2 + length * Math.sin(angle * Math.PI / 180 - Math.PI / 2);
      ctx.lineTo(x, y);
      ctx.strokeStyle = '#333';
      ctx.lineWidth = 2;
      ctx.stroke();
    }
  }
};
</script>
<p>在这个示例中,我们使用 Vue 的生命周期钩子函数 'mounted' 来在组件挂载后绘制倒计时。在 'drawCountdown' 方法中,我们首先获取 Canvas 的上下文 'ctx',然后绘制倒计时的背景。接着,获取当前的小时、分钟和秒数,并分别绘制时针、分针和秒针。'drawClock' 方法用于绘制时钟的刻度和数字,'drawHand' 方法用于绘制指针。最后,我们在模板中使用 'ref' 属性引用 Canvas 元素,并在 'mounted' 方法中调用 'drawCountdown' 方法来绘制倒计时。</p>
Vue Canvas 倒计时绘制 - 实时时钟显示

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

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