使用svg中的polygon元素来画一个六边形步骤
- 先准备好svg和一个polygon元素,设置其填充色。
<svg width="400" height="400" id="container">
<polygon id="hexagon" fill="#007175"></polygon>
</svg>
- 封装公共方法,求六边形的六个点的坐标。可以通过传入的percent参数,调整六边形占据容器的比例大小。范围:0~1。
const calculateHexagonPoints = (percent) => {
const ele = document.getElementById('container')
const width = ele.clientWidth
const height = ele.clientHeight
const centerX = width / 2
const centerY = height / 2
const sideLength = Math.min(width, height) / 2 * percent
const points = []
for (let i = 0; i < 6; i++) {
const angle = (i * Math.PI * 2) / 6
const x = centerX + sideLength * Math.cos(angle)
const y = centerY + sideLength * Math.sin(angle)
points.push(`${x}, ${y}`)
}
return points.join(' ')
}
- 获取polygon元素,设置坐标点。
const polygon = document.getElementById('hexagon')
polygon.setAttribute('points', calculateHexagonPoints(1))
效果

完整代码
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>六边形</title>
</head>
<body>
<svg width="400" height="400" id="container">
<polygon id="hexagon" fill="#007175"></polygon>
</svg>
</body>
<script>
const calculateHexagonPoints = (percent) => {
const ele = document.getElementById('container')
const width = ele.clientWidth
const height = ele.clientHeight
const centerX = width / 2
const centerY = height / 2
const sideLength = Math.min(width, height) / 2 * percent
const points = []
for (let i = 0; i < 6; i++) {
const angle = (i * Math.PI * 2) / 6
const x = centerX + sideLength * Math.cos(angle)
const y = centerY + sideLength * Math.sin(angle)
points.push(`${x}, ${y}`)
}
return points.join(' ')
}
const polygon = document.getElementById('hexagon')
polygon.setAttribute('points', calculateHexagonPoints(1))
</script>
</html>