highlight: an-old-hope
theme: healer-readable
最近有一个圆环进度,和倒计时的需求,准备使用svg
来实现,但是之前没有接触过它
今天就准备以目标为导向,来学习了解svg的一些简单用法,并且来实现它
从画方块开始
svg
不设置宽高时默认宽度
是 300px ,默认高度
是 150px
<template>
<svg class="box" >
</svg>
</template>
<style scoped>
.box {
border: 1px solid red;
}
</style>
也可以在 svg
上添加 width 和 height
两个属性设置宽高,默认是px,也可以带其他单位
<svg width="100" height="100">
</svg>
svg就相当于一个画布,画布的大小设置好了,我们就可以在上面作画了,先画一个圆吧
画个圆
圆使用 <circle>
标签,默认填充色是黑色,当只设置半径r
时,渲染出来的圆就是黑色的圆
<svg width="100" height="100" class="box" >
<circle
r="50"
/>
</svg>
此时我们可以看到圆的中心点在左上角,所以只显示了1/4,需要给圆一个位置 cx和cy
,我想要把圆的背景变成红色,显得喜庆,就需要用到fill
属性,进行填充颜色
<svg width="100" height="100" >
<circle
cx="50"
cy="50"
r="50"
fill='red'
/>
</svg>
圆环
stroke
是用来描边填充的颜色,和border类似
stroke-width
相当于描边的宽度,但是它不属于半径
可以用这两个属性画一个圆环
<svg width="100" height="100" class="box">
<circle
cx="50"
cy="50"
r="45"
fill='none'
stroke="red"
stroke-width="10"
/>
</svg>
stroke-width
设置的宽度,一半在圆内,一半在圆外
动起来
圆环进度和倒计时,主要要依靠stroke-dasharray
这个属性来实现
stroke-dasharray
stroke-dasharray
设置实线和间隔的距离
stroke-dasharray: 20, 5;
表示按照实线为 20,间隔为 5 的排列重复下去
<svg width="200" height="200" >
<circle
cx="100"
cy="100"
r="50"
fill='none'
stroke="red"
stroke-width="10"
stroke-dasharray="20, 5"
/>
</svg>
当间隔等于圆的周长,实线从0开始增加
<svg width="200" height="200" >
<circle
cx="100"
cy="100"
r="50"
fill="green"
stroke-width="10"
stroke="red"
stroke-dasharray="29.1719, 314.1592653589793"
/>
</svg>
开始实现动态加载
常见的圆环进度通常都是默认两种颜色,一种是初始值,另一种是加载进度的颜色,我们可以使用两个圆,把他们的半径和位置等属性设置相同,只改变两个圆的颜色
- 第一个
circle
设置边框颜色设置为灰色 - 第二个
circle
设置为红色,好区分
<svg width="200" height="200" >
<circle
cx="100"
cy="100"
r="50"
fill="none"
stroke="#808080"
stroke-width="10"
/>
<circle
cx="100"
cy="100"
r="50"
fill="none"
stroke-width="10"
stroke="red"
stroke-dasharray="20, 314.1592653589793"
/>
</svg>
基础框架已经搭建好了,现在要让他动起来,我们可以用计算属性设置红色的实线长度
圆周长是 2πr这就是它的间隔,然后根据时间计算实线的距离
<template>
<svg width="200" height="200" >
<circle
cx="100"
cy="100"
r="50"
fill="none"
stroke="#808080"
stroke-width="10"
/>
<circle
cx="100"
cy="100"
r="50"
fill="none"
stroke-width="10"
:style="{
stroke:'red',
strokeDasharray: `${currentLen} ${circleLength}`
}"
/>
</svg>
</template>
<script setup>
import { ref } from 'vue'
// 圆周长 2πr
const circleLength = 2 * Math.PI * 50
const time = 6 // 倒计时 6秒
let currentT = ref(0) // 当前时间
let currentLen = ref(0) // 当前长度
let timeId = setInterval(() => {
currentT.value++
// 计算长度
currentLen.value = currentT.value / time * circleLength
if(currentT.value>time) {
clearInterval(timeId)
}
}, 1000);
</script>
虽然说可以实现效果,但是动画太生硬,接下来可以使用动画属性把动效变顺畅一些
在style里添加transition
属性来增加动画效果
:style="{
stroke:'red',
strokeDasharray: `${currentLen} ${circleLength}`,
transition: 'all 1s linear',
}"
如果觉得圆环线头的类型不太好看,可以使用stroke-linecap
属性来修改
:style="{
stroke:'red',
strokeDasharray: `${currentLen} ${circleLength}`,
transition: 'all 1s linear',
strokeLinecap:'round',
}"
至此一个简化版的圆环进度的主要功能就已经实现了,剩下的就是一些边边角角可以自由发挥了
本文正在参加「金石计划 . 瓜分6万现金大奖」
暂无评论内容