vue菱形图实现
Vue 实现菱形图的方法
使用 CSS transform 旋转正方形
通过 CSS 的 transform 属性将正方形旋转 45 度即可生成菱形。在 Vue 中可以通过动态绑定样式实现。
<template>
<div class="diamond-container">
<div
v-for="(item, index) in items"
:key="index"
class="diamond"
:style="{ backgroundColor: item.color }"
>
{{ item.label }}
</div>
</div>
</template>
<script>
export default {
data() {
return {
items: [
{ label: 'A', color: '#ff7675' },
{ label: 'B', color: '#74b9ff' },
{ label: 'C', color: '#55efc4' }
]
}
}
}
</script>
<style>
.diamond-container {
display: flex;
gap: 20px;
}
.diamond {
width: 100px;
height: 100px;
display: flex;
justify-content: center;
align-items: center;
transform: rotate(45deg);
color: white;
font-weight: bold;
}
.diamond span {
transform: rotate(-45deg);
}
</style>
使用 SVG 绘制菱形
SVG 的 polygon 元素可以精确绘制菱形,通过 Vue 动态生成 points 属性。
<template>
<svg width="300" height="200">
<polygon
v-for="(item, index) in items"
:key="index"
:points="getDiamondPoints(index)"
:fill="item.color"
/>
<text
v-for="(item, index) in items"
:key="'text-' + index"
:x="50 + index * 100"
:y="100"
fill="white"
text-anchor="middle"
>
{{ item.label }}
</text>
</svg>
</template>
<script>
export default {
data() {
return {
items: [
{ label: 'X', color: '#e84393' },
{ label: 'Y', color: '#0984e3' },
{ label: 'Z', color: '#00b894' }
]
}
},
methods: {
getDiamondPoints(index) {
const x = 50 + index * 100
return `${x},50 ${x+40},100 ${x},150 ${x-40},100`
}
}
}
</script>
使用 Canvas 绘制
通过 Canvas 的路径绘制功能可以创建菱形图形,适合需要动态交互的场景。
<template>
<canvas ref="canvas" width="400" height="200"></canvas>
</template>
<script>
export default {
mounted() {
this.drawDiamonds()
},
data() {
return {
diamonds: [
{ x: 50, y: 100, size: 40, color: '#fdcb6e' },
{ x: 150, y: 100, size: 40, color: '#e17055' },
{ x: 250, y: 100, size: 40, color: '#6c5ce7' }
]
}
},
methods: {
drawDiamonds() {
const ctx = this.$refs.canvas.getContext('2d')
this.diamonds.forEach(d => {
ctx.beginPath()
ctx.moveTo(d.x, d.y - d.size)
ctx.lineTo(d.x + d.size, d.y)
ctx.lineTo(d.x, d.y + d.size)
ctx.lineTo(d.x - d.size, d.y)
ctx.closePath()
ctx.fillStyle = d.color
ctx.fill()
})
}
}
}
</script>
使用第三方图表库
对于复杂的菱形图表,可以使用 ECharts 等专业图表库,通过配置项实现菱形系列。
<template>
<div ref="chart" style="width: 600px; height: 400px;"></div>
</template>
<script>
import * as echarts from 'echarts'
export default {
mounted() {
this.initChart()
},
methods: {
initChart() {
const chart = echarts.init(this.$refs.chart)
const option = {
series: [{
type: 'scatter',
symbol: 'diamond',
symbolSize: 30,
data: [
[10, 20],
[30, 40],
[50, 60]
],
itemStyle: {
color: function(params) {
const colors = ['#a29bfe', '#fd79a8', '#ffeaa7']
return colors[params.dataIndex]
}
}
}]
}
chart.setOption(option)
}
}
}
</script>
这些方法涵盖了从基础 CSS 实现到专业图表库的应用,可以根据项目需求选择适合的方案。CSS 方案适合简单展示,SVG/Canvas 适合需要自定义交互的场景,而图表库则适合数据可视化需求。







