使用svg画六边形

发布于:2024-05-23 ⋅ 阅读:(85) ⋅ 点赞:(0)

使用svg中的polygon元素来画一个六边形步骤

  1. 先准备好svg和一个polygon元素,设置其填充色。
<svg width="400" height="400" id="container">
    <polygon id="hexagon" fill="#007175"></polygon>
</svg>
  1. 封装公共方法,求六边形的六个点的坐标。可以通过传入的percent参数,调整六边形占据容器的比例大小。范围:0~1。
/**
 * @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(' ')
}
  1. 获取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>
    /**
     * @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(' ')
    }

    // 获取多边形元素
    const polygon = document.getElementById('hexagon')
    // 设置点坐标
    polygon.setAttribute('points', calculateHexagonPoints(1))

</script>

</html>

网站公告

今日签到

点亮在社区的每一天
去签到