如何生成N边(等长和角度)的多边形

问题描述 投票:-2回答:1

我正在寻找一种方法来计算正多边形的SVG路径,给定边数,包装容器的宽度和高度。

任何帮助将非常感谢!

谢谢,最好。

更新:N可以是偶数也可以是奇数。

javascript math svg geometry polygon
1个回答
0
投票

步骤1.如何创建SVG

 const $svg = document.createElementNS("http://www.w3.org/2000/svg", "svg")
 $svg.setAttributeNS("http://www.w3.org/2000/xmlns/", "xmlns:xlink", "http://www.w3.org/1999/xlink")
 $svg.setAttribute('width', 500)
 $svg.setAttribute('height', 500)
 $svg.setAttribute('viewBox', '0 0 500 500')
 document.body.appendChild($svg)

第2步。如何创建Line

const $el= document.createElementNS("http://www.w3.org/2000/svg", "line")
$el.setAttribute('x1', 0)
$el.setAttribute('y1', 0)
$el.setAttribute('x2', 100) // not real
$el.setAttribute('y2', 100) // not real
$svg.appendChild($el)

第3步。如何创建真正的Line

function (sides, width) {
    const angle = 360 / sides

    const $el1= document.createElementNS("http://www.w3.org/2000/svg", "line")
    $el1.setAttribute('x1', 0)
    $el1.setAttribute('y1', 0)
    $el1.setAttribute('x2', width)
    $el1.setAttribute('y2', 0)
    $svg.appendChild($el1)

    // we already created first line, so start from 1
    for (var i = 1; i < sides.length; i++) { 
        const $el= document.createElementNS("http://www.w3.org/2000/svg", "line")     
        const offsetX_angle = 180 - angle
        const hypotenuse = width / Math.sin(90)
        const offsetX = Math.sin(90 - offsetX_angle) * hypotenuse
        const offsetY = Math.sin(offsetX_angle) * hypotenuse

        // now we know the offsets
        // and we can easily populate other lines using same offset
        const x1 = width
        const y1 = 0
        const x2 = width + offsetX
        const y2 = 0 + offsetY

        // just need to switch angles based in i
    }
}

这不是完整的解决方案,而是制定解决方案的步骤

enter image description here

© www.soinside.com 2019 - 2024. All rights reserved.