Vue 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>
<p>在上面的示例中,首先定义了一个 canvas 元素和一个显示剩余时间的 div 元素。然后在 mounted 钩子函数中调用了 drawTimer 方法绘制倒计时的圆圈。drawTimer 方法使用 canvas 的 getContext 方法获取绘图上下文,然后使用 arc 方法绘制圆圈,并根据剩余时间计算出需要绘制的圆弧的结束角度,填充颜色为红色。</p>
<p>接着在 startTimer 方法中使用 setInterval 方法每秒减少剩余时间并重新绘制倒计时的圆弧,直到剩余时间为 0 时清除计时器。</p>
<p>最后,在样式中设置 canvas 的边框样式。</p>
原文地址: https://www.cveoy.top/t/topic/qgRS 著作权归作者所有。请勿转载和采集!