封装一个公共方法,根据容器大小,和比例求取六边形的六个点的坐标。
代码
/**
* @description 求六边形的六个点的坐标
* @author Joyce Lee
* @date 2024-5-23
* @param percent 六边形占据容器大小的比例
* @return points 点坐标 400, 200 300, 373.2050807568877 100.00000000000004, 373.20508075688775 0, 200.00000000000003 99.99999999999991, 26.794919243112332 300, 26.794919243112275
*/
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(' ')
}
示例
console.log(calculateHexagonPoints(1))
// 400, 200 300, 373.2050807568877 100.00000000000004, 373.20508075688775 0, 200.00000000000003 99.99999999999991, 26.794919243112332 300, 26.794919243112275
console.log(calculateHexagonPoints(0.8))
// 360, 200 280, 338.56406460551017 120.00000000000003, 338.5640646055102 40, 200.00000000000003 119.99999999999993, 61.43593539448986 280, 61.43593539448983
console.log(calculateHexagonPoints(0.7))
// 340, 200 270, 321.2435565298214 130.00000000000003, 321.24355652982143 60, 200.00000000000003 129.99999999999994, 78.75644347017862 270, 78.7564434701786