canvas绘制圆形进度条
用canvas绘制了一个圆形进度条,记录一下:
效果如下:
感觉效果还行,不过有待优化
代码如下:
我是用Vue写的
组件的代码:
progressCanvas.vue
<template>
<div>
<canvas id="progressCanvas" width="200" height="200"></canvas>
</div>
</template>
<script>
export default {
name: 'ProgressCanvas',
data() {
return {
drawPgress: 0
}
},
mounted() {
const aa = setInterval(() => {
this.drawProgress(this.drawPgress += 0.01) // 传入一个0到1之间的数字来表示进度
if (this.drawPgress > 1) {
clearInterval(aa)
}
}, 100)
// this.drawProgress(0.8)
},
methods: {
drawProgress(progress) {
const canvas = document.getElementById('progressCanvas')
if (canvas.getContext) {
const ctx = canvas.getContext('2d')
const x = canvas.width / 2
const y = canvas.height / 2
const radius = 90
const startAngle = -0.5 * Math.PI // 从顶部开始
const endAngle = (-0.5 + 2 * progress) * Math.PI
// 清除画布
ctx.clearRect(0, 0, canvas.width, canvas.height)
// 绘制圆形进度条背景
ctx.beginPath()
ctx.arc(x, y, radius, 0, 2 * Math.PI)
ctx.lineWidth = 10
ctx.strokeStyle = '#5D52E1'
ctx.stroke()
// 计算渐变色的起始和结束坐标
const gradientStartX = x + radius * Math.cos(startAngle)
const gradientStartY = y + radius * Math.sin(startAngle)
const gradientEndX = x + radius * Math.cos(endAngle)
const gradientEndY = y + radius * Math.sin(endAngle)
// 创建渐变色
const gradient = ctx.createLinearGradient(gradientStartX, gradientStartY, gradientEndX, gradientEndY)
gradient.addColorStop(0, '#5D52E1')
gradient.addColorStop(1, '#FFFFFF')
// 绘制圆形进度条
ctx.beginPath()
ctx.arc(x, y, radius, startAngle, endAngle)
ctx.lineWidth = 10
ctx.strokeStyle = gradient
ctx.stroke()
}
}
}
}
</script>
<style lang="scss" scoped>
</style>
OK,实现完毕!如果大家有什么更好的想法可以交流一下