vue3使用canvas写一个类似网易云音乐app的圆形的音乐播放进度条
时间: 2024-05-05 16:21:39 浏览: 62
好的,下面是一个简单的示例代码,可以实现一个类似网易云音乐app的圆形的音乐播放进度条:
首先,我们需要在 Vue 组件中引入 Canvas 元素,并在组件中定义一个 Canvas 上下文对象:
```html
<template>
<div>
<canvas ref="canvas" width="200" height="200"></canvas>
</div>
</template>
<script>
export default {
name: 'Progress',
mounted() {
this.canvas = this.$refs.canvas
this.ctx = this.canvas.getContext('2d')
},
methods: {
drawProgress(percent) {
// 绘制圆形进度条
const centerX = this.canvas.width / 2
const centerY = this.canvas.height / 2
const radius = 80
const startAngle = -Math.PI / 2
const endAngle = startAngle + (Math.PI * 2) * percent
this.ctx.clearRect(0, 0, this.canvas.width, this.canvas.height)
this.ctx.beginPath()
this.ctx.arc(centerX, centerY, radius, startAngle, endAngle)
this.ctx.strokeStyle = '#fff'
this.ctx.lineWidth = 10
this.ctx.stroke()
}
}
}
</script>
```
接下来,我们可以通过传递一个百分比值来绘制进度条:
```html
<template>
<div>
<canvas ref="canvas" width="200" height="200"></canvas>
<div>{{ percent }}%</div>
</div>
</template>
<script>
export default {
name: 'Progress',
props: {
percent: {
type: Number,
required: true,
default: 0
}
},
mounted() {
this.canvas = this.$refs.canvas
this.ctx = this.canvas.getContext('2d')
this.drawProgress(this.percent / 100)
},
watch: {
percent(newValue) {
this.drawProgress(newValue / 100)
}
},
methods: {
drawProgress(percent) {
// 绘制圆形进度条
const centerX = this.canvas.width / 2
const centerY = this.canvas.height / 2
const radius = 80
const startAngle = -Math.PI / 2
const endAngle = startAngle + (Math.PI * 2) * percent
this.ctx.clearRect(0, 0, this.canvas.width, this.canvas.height)
this.ctx.beginPath()
this.ctx.arc(centerX, centerY, radius, startAngle, endAngle)
this.ctx.strokeStyle = '#fff'
this.ctx.lineWidth = 10
this.ctx.stroke()
}
}
}
</script>
```
这样,我们就可以在组件中传递一个 `percent` 属性,来实现动态绘制进度条的效果了。
阅读全文