<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)
}
});