vue实现蜂窝图
Vue 实现蜂窝图的方法
蜂窝图(Hexagon Grid)通常用于数据可视化或游戏界面,以下是几种实现方式:
使用 SVG 绘制蜂窝网格
通过 SVG 的 <polygon> 元素可以精确绘制六边形:

<template>
<svg width="500" height="500">
<polygon
v-for="(hex, index) in hexagons"
:key="index"
:points="getHexPoints(hex.x, hex.y, size)"
fill="#4CAF50"
stroke="#333"
/>
</svg>
</template>
<script>
export default {
data() {
return {
size: 30, // 六边形边长
hexagons: [] // 存储六边形中心坐标
};
},
mounted() {
this.generateGrid(5, 5); // 生成5x5网格
},
methods: {
getHexPoints(x, y, size) {
const points = [];
for (let i = 0; i < 6; i++) {
const angle = Math.PI / 3 * i;
points.push(
(x + size * Math.cos(angle)).toFixed(2),
(y + size * Math.sin(angle)).toFixed(2)
);
}
return points.join(' ');
},
generateGrid(rows, cols) {
const offsetX = this.size * 1.5;
const offsetY = this.size * Math.sqrt(3);
for (let r = 0; r < rows; r++) {
for (let c = 0; c < cols; c++) {
this.hexagons.push({
x: c * offsetX + (r % 2) * offsetX / 2,
y: r * offsetY * 0.75
});
}
}
}
}
};
</script>
使用 CSS 实现蜂窝布局
通过 CSS 的 clip-path 属性和网格布局:
<template>
<div class="honeycomb">
<div
v-for="(item, index) in items"
:key="index"
class="hexagon"
:style="{ backgroundColor: item.color }"
>
{{ item.label }}
</div>
</div>
</template>
<style>
.honeycomb {
display: flex;
flex-wrap: wrap;
gap: 4px;
width: 300px;
}
.hexagon {
width: 100px;
height: 115px;
background: #3498db;
position: relative;
clip-path: polygon(
25% 0%, 75% 0%,
100% 50%, 75% 100%,
25% 100%, 0% 50%
);
display: flex;
align-items: center;
justify-content: center;
color: white;
}
</style>
使用第三方库(如 vue-hexagon)
对于快速实现,可以安装专用库:

npm install vue-hexagon
示例代码:
<template>
<vue-hexagon
v-for="(hex, i) in hexData"
:key="i"
:x="hex.x"
:y="hex.y"
:radius="30"
:fill="hex.color"
/>
</template>
<script>
import VueHexagon from 'vue-hexagon';
export default {
components: { VueHexagon },
data() {
return {
hexData: [
{ x: 50, y: 50, color: '#e74c3c' },
{ x: 100, y: 90, color: '#3498db' }
]
};
}
};
</script>
交互功能增强
为蜂窝添加点击事件和数据绑定:
<template>
<svg width="500" height="500">
<polygon
v-for="(hex, index) in hexagons"
:key="index"
:points="getHexPoints(hex.x, hex.y, size)"
:fill="hex.active ? '#e74c3c' : '#3498db'"
@click="toggleHex(index)"
/>
</svg>
</template>
<script>
export default {
methods: {
toggleHex(index) {
this.$set(this.hexagons[index], 'active', !this.hexagons[index].active);
}
}
};
</script>
关键注意事项
- 坐标计算:六边形中心点坐标需遵循 $x = 1.5 \times size \times column$ 和 $y = \sqrt{3} \times size \times (row + 0.5 \times (column \% 2))$ 的规律
- 性能优化:大数据量时建议使用 Canvas 而非 SVG
- 响应式设计:通过监听窗口大小变化重新计算网格布局






