vue实现圆刻度
Vue实现圆刻度的方法
使用SVG绘制圆形刻度
通过SVG的<circle>和<path>元素可以创建精确的圆形刻度。这种方法适合需要高精度和自定义样式的场景。

<template>
<svg width="200" height="200" viewBox="0 0 200 200">
<circle cx="100" cy="100" r="90" fill="none" stroke="#eee" stroke-width="2"/>
<!-- 刻度线 -->
<path
v-for="(item, index) in 12"
:key="index"
:d="getTickPath(index * 30, 80, 90)"
stroke="#333"
stroke-width="2"
/>
</svg>
</template>
<script>
export default {
methods: {
getTickPath(angle, innerRadius, outerRadius) {
const rad = (angle * Math.PI) / 180
const x1 = 100 + innerRadius * Math.sin(rad)
const y1 = 100 - innerRadius * Math.cos(rad)
const x2 = 100 + outerRadius * Math.sin(rad)
const y2 = 100 - outerRadius * Math.cos(rad)
return `M${x1},${y1} L${x2},${y2}`
}
}
}
</script>
使用CSS transform旋转元素
通过CSS的transform属性旋转div元素来创建刻度。这种方法实现简单,适合不需要高精度的场景。

<template>
<div class="clock-face">
<div
v-for="(item, index) in 60"
:key="index"
class="tick"
:style="{ transform: `rotate(${index * 6}deg)` }"
></div>
</div>
</template>
<style>
.clock-face {
width: 200px;
height: 200px;
border-radius: 50%;
position: relative;
background: #f5f5f5;
}
.tick {
position: absolute;
top: 0;
left: 50%;
width: 2px;
height: 10px;
background: #333;
transform-origin: 0 100px;
}
</style>
使用Canvas绘制圆形刻度
Canvas API提供了更灵活的绘图能力,适合需要动态更新或复杂交互的场景。
<template>
<canvas ref="canvas" width="200" height="200"></canvas>
</template>
<script>
export default {
mounted() {
this.drawTicks()
},
methods: {
drawTicks() {
const canvas = this.$refs.canvas
const ctx = canvas.getContext('2d')
const centerX = canvas.width / 2
const centerY = canvas.height / 2
const radius = 90
ctx.beginPath()
ctx.arc(centerX, centerY, radius, 0, 2 * Math.PI)
ctx.strokeStyle = '#eee'
ctx.stroke()
for (let i = 0; i < 12; i++) {
const angle = (i * 30) * Math.PI / 180
ctx.beginPath()
ctx.moveTo(
centerX + (radius - 10) * Math.sin(angle),
centerY - (radius - 10) * Math.cos(angle)
)
ctx.lineTo(
centerX + radius * Math.sin(angle),
centerY - radius * Math.cos(angle)
)
ctx.strokeStyle = '#333'
ctx.stroke()
}
}
}
}
</script>
使用第三方库(如D3.js)
对于复杂的数据可视化需求,可以集成D3.js等专业图表库。
<template>
<div ref="chart"></div>
</template>
<script>
import * as d3 from 'd3'
export default {
mounted() {
this.initChart()
},
methods: {
initChart() {
const svg = d3.select(this.$refs.chart)
.append('svg')
.attr('width', 200)
.attr('height', 200)
const g = svg.append('g').attr('transform', 'translate(100,100)')
const scale = d3.scaleLinear()
.domain([0, 12])
.range([0, 2 * Math.PI])
g.selectAll('line')
.data(d3.range(12))
.enter()
.append('line')
.attr('x1', 0)
.attr('y1', -80)
.attr('x2', 0)
.attr('y2', -90)
.attr('transform', d => `rotate(${scale(d) * 180/Math.PI})`)
.attr('stroke', '#333')
}
}
}
</script>






