vue实现蜂窝图
Vue 实现蜂窝图
实现蜂窝图(Hexagonal Grid)在 Vue 中可以通过 SVG 或 CSS 布局完成。以下是两种常见的方法:

使用 SVG 绘制蜂窝图
通过 SVG 的 polygon 元素绘制六边形,并动态计算位置:
<template>
<svg :width="width" :height="height">
<g v-for="(hex, index) in hexagons" :key="index" :transform="`translate(${hex.x}, ${hex.y})`">
<polygon
:points="hexPoints"
fill="#4CAF50"
stroke="#2E7D32"
@click="handleHexClick(index)"
/>
<text x="0" y="5" text-anchor="middle" fill="white">{{ index + 1 }}</text>
</g>
</svg>
</template>
<script>
export default {
data() {
return {
width: 600,
height: 400,
radius: 30, // 六边形半径
hexagons: [] // 存储六边形坐标
};
},
computed: {
hexPoints() {
const points = [];
for (let i = 0; i < 6; i++) {
const angle = (Math.PI / 3) * i;
const x = this.radius * Math.cos(angle);
const y = this.radius * Math.sin(angle);
points.push(`${x},${y}`);
}
return points.join(" ");
}
},
mounted() {
this.generateHexGrid(5, 5); // 生成5x5的蜂窝网格
},
methods: {
generateHexGrid(rows, cols) {
const hexHeight = this.radius * 2;
const hexWidth = Math.sqrt(3) * this.radius;
const horizontalSpacing = hexWidth * 0.75;
const verticalSpacing = hexHeight * 0.5;
for (let row = 0; row < rows; row++) {
for (let col = 0; col < cols; col++) {
const x = col * horizontalSpacing;
const y = row * verticalSpacing + (col % 2) * (hexHeight / 2);
this.hexagons.push({ x, y });
}
}
},
handleHexClick(index) {
console.log(`Hexagon ${index + 1} clicked`);
}
}
};
</script>
使用 CSS 实现蜂窝图
通过 CSS 的 clip-path 属性创建六边形效果:
<template>
<div class="hex-grid">
<div
v-for="(hex, index) in hexagons"
:key="index"
class="hexagon"
:style="{
left: `${hex.x}px`,
top: `${hex.y}px`
}"
@click="handleHexClick(index)"
>
{{ index + 1 }}
</div>
</div>
</template>
<script>
export default {
data() {
return {
hexWidth: 60,
hexHeight: 70,
hexagons: []
};
},
mounted() {
this.generateHexGrid(5, 5);
},
methods: {
generateHexGrid(rows, cols) {
const horizontalSpacing = this.hexWidth * 0.75;
const verticalSpacing = this.hexHeight * 0.5;
for (let row = 0; row < rows; row++) {
for (let col = 0; col < cols; col++) {
const x = col * horizontalSpacing;
const y = row * verticalSpacing + (col % 2) * (this.hexHeight / 2);
this.hexagons.push({ x, y });
}
}
},
handleHexClick(index) {
console.log(`Hexagon ${index + 1} clicked`);
}
}
};
</script>
<style>
.hex-grid {
position: relative;
width: 600px;
height: 400px;
margin: 0 auto;
}
.hexagon {
position: absolute;
width: 60px;
height: 70px;
background-color: #4CAF50;
clip-path: polygon(
25% 0%,
75% 0%,
100% 50%,
75% 100%,
25% 100%,
0% 50%
);
display: flex;
justify-content: center;
align-items: center;
color: white;
cursor: pointer;
transition: background-color 0.3s;
}
.hexagon:hover {
background-color: #2E7D32;
}
</style>
关键点说明
- 六边形坐标计算:蜂窝网格需要交错排列,奇数行和偶数行的垂直偏移不同。
- 交互处理:通过
@click事件实现六边形的点击交互。 - 响应式设计:可以根据容器尺寸动态调整蜂窝图的大小和位置。
这两种方法各有优势,SVG 适合复杂的图形操作,CSS 方法则更轻量且易于与现有样式集成。







