微信小程序实现倒计时功能

<canvas id="myCanvas" type="2d" style="border: 1px solid; width: 300px; height: 300px;" />
Page({
  date: Date.now() + 10*1000,
  canvas: null,
  canvasWith: 0,
  canvasHeight: 0,
  cxt: null,
  animationId: 0,
  onLoad() {
    this.startCountdown();
  },
  onUnload() {
    this.endCountdown()
  },
  startCountdown () {
    // 获取 canvas
     this.createSelectorQuery().select('#myCanvas').fields({ node: true }).exec((res) => {
      this.canvas = res[0].node
      this.canvasWith = this.canvas.width
      this.canvasHeight = this.canvas.height
      this.cxt = this.canvas.getContext('2d')
      this.animationId = this.canvas.requestAnimationFrame(() => {
        this.updateCountdown()
      });
    })
  },
  updateCountdown ()  {
    const currentTime = Date.now()
    const timeRemaining = this.date - currentTime

    // 倒计时结束
    if (timeRemaining <= 0) {
      console.log('countdown finish')
      this.endCountdown()
      return
    } 

    // 将倒计时的时间绘制到 canvas 上
    this.cxt.clearRect(0, 0, this.canvasWith, this.canvasHeight)
    this.cxt.fillText(Math.floor(timeRemaining / 1000), 150, 150)

    // 递归调用自身
    this.animationId = this.canvas.requestAnimationFrame(() => {
      this.updateCountdown()
    });
  },
  endCountdown() {
    this.canvas.cancelAnimationFrame(this.animationId)
  }
});
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值