vue canvas 绘制倒计时
以下是一个使用Vue和Canvas绘制倒计时的示例代码:
<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>
在这个示例中,我们使用Vue的生命周期钩子函数mounted来在组件挂载后绘制倒计时。在drawCountdown方法中,我们首先获取Canvas的上下文ctx,然后绘制倒计时的背景。接着,获取当前的小时、分钟和秒数,并分别绘制时针、分针和秒针。drawClock方法用于绘制时钟的刻度和数字,drawHand方法用于绘制指针。最后,我们在模板中使用ref属性引用Canvas元素,并在mounted方法中调用drawCountdown方法来绘制倒计时
原文地址: https://www.cveoy.top/t/topic/izMC 著作权归作者所有。请勿转载和采集!