请帮我用scss+vue3实现精美的圆形倒计时
时间: 2024-03-08 10:49:54 浏览: 77
好的,下面是一个用scss+vue3实现精美的圆形倒计时的示例代码:
```vue
<template>
<div class="countdown">
<canvas ref="canvas"></canvas>
<div class="countdown-text">{{ time }}</div>
</div>
</template>
<script>
import { ref, watchEffect } from 'vue'
export default {
setup() {
const canvas = ref(null)
const time = ref('00:00')
const totalTime = 60 // 总时间
const interval = 1000 // 刷新间隔
const radius = 70 // 半径
const lineWidth = 8 // 圆环宽度
const bgColor = '#f0f0f0' // 背景色
const fgColor = '#ff5722' // 前景色
const start = Date.now() // 开始时间
let timer = null // 定时器
// 格式化时间
function formatTime(time) {
let minute = Math.floor(time / 60)
let second = time % 60
minute = minute < 10 ? '0' + minute : minute
second = second < 10 ? '0' + second : second
return minute + ':' + second
}
// 绘制圆环
function drawCircle(percent) {
const ctx = canvas.value.getContext('2d')
const centerX = canvas.value.width / 2
const centerY = canvas.value.height / 2
const angle = percent * 2 * Math.PI - Math.PI / 2
// 绘制背景圆环
ctx.beginPath()
ctx.arc(centerX, centerY, radius, 0, 2 * Math.PI)
ctx.lineWidth = lineWidth
ctx.strokeStyle = bgColor
ctx.stroke()
// 绘制前景圆环
ctx.beginPath()
ctx.arc(centerX, centerY, radius, -Math.PI / 2, angle)
ctx.lineWidth = lineWidth
ctx.strokeStyle = fgColor
ctx.stroke()
}
// 更新时间和圆环
function updateTime() {
const now = Date.now()
const elapsed = Math.floor((now - start) / interval)
const remaining = totalTime - elapsed
const percent = elapsed / totalTime
if (remaining > 0) {
time.value = formatTime(remaining)
drawCircle(percent)
} else {
clearInterval(timer)
}
}
watchEffect(() => {
if (canvas.value) {
canvas.value.width = radius * 2
canvas.value.height = radius * 2
updateTime()
timer = setInterval(updateTime, interval)
}
})
return {
canvas,
time,
}
},
}
</script>
<style lang="scss" scoped>
.countdown {
position: relative;
width: 150px;
height: 150px;
margin: 0 auto;
.countdown-text {
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
font-size: 28px;
font-weight: bold;
color: #333;
}
}
</style>
```
这个示例代码中,通过canvas绘制圆环,使用watchEffect监听canvas的变化,在更新时间和圆环的时候重新绘制canvas。同时,使用setup函数来定义组件的逻辑。最终实现了一个精美的圆形倒计时效果。
阅读全文